In this tutorial, we will learn we will check how to convert a decimal number to binary.
How to convert a decimal number to binary: The entered number in decimal repeatedly divided by 2 and its binary form is obtained.
Here is source code of the C# Program to Convert Integer Number to Binary:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Program { static void Main(string[] args) { int number; Console.Write("Enter a Number : "); number = int.Parse(Console.ReadLine()); int q; string rem = ""; while (number >= 1) { q = number / 2; rem += (number % 2).ToString(); number = q; } string binary = ""; for (int i = rem.Length - 1; i >= 0; i--) { binary = binary + rem[i]; } Console.WriteLine("The Binary format for {0} is {1}",number, binary); Console.ReadLine(); } } |
Other way: You can convert decimal to number, If you want to without think any algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Program { static void Main(string[] args) { Console.Write("Enter a number : "); int number = Convert.ToInt32(Console.ReadLine()); string binary = Convert.ToString(number, 2); Console.WriteLine("The Binary format for {0} is {1}",number, binary); Console.ReadLine(); } } |
Output: