C# Program to Convert Decimal to Binary\\n



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#.

Live Demo

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
Updated on: 2020-06-19T09:28:41+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements