- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to Convert Decimal to Binary
Let’ s say you have set the decimal to be −
decVal = 34; Console.WriteLine("Decimal: {0}", decVal);
Use the ToString() method for the values you get as a binary number for the decimal value −
while (decVal >= 1) { val = decVal / 2; a += (decVal % 2).ToString(); decVal = val; }
Now set a new empty variable to display the binary number using a loop −
string binValue = "";
Example
You can try to run the following code to convert decimal to binary in C#.
using System; using System.Collections.Generic; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int decVal; int val; string a = ""; decVal = 34; Console.WriteLine("Decimal: {0}", decVal); while (decVal >= 1) { val = decVal / 2; a += (decVal % 2).ToString(); decVal = val; } string binValue = ""; for (int i = a.Length - 1; i >= 0; i--) { binValue = binValue + a[i]; } Console.WriteLine("Binary: {0}", binValue); Console.Read(); } } }
Output
Decimal: 34 Binary: 100010
Advertisements