Decimal to Binary in C Sharp

Decimal to Binary

A decimal or a base-10 number can be converted into binary or base-2 number in C#.

Decimal Number:

A decimal number ranges from 0 to 9. It can be any combination of the 10 digits between 0 to 9. Thus it is a base 10 number.

Binary Number:

A binary number is either 0 or 1 or a combination of 0 and 1. Thus it is a base 2 number.

The binary numbers for some decimal numbers are listed below.

Decimal Binary
1 0
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

Algorithm:

Step 1: The number is divided by 2 using the

Step 2: The number is divided by 2 using the / (division operator).

Step 3: Step 2 is repeated until the number becomes less than zero.

Example:

using System;  
  public class Example  
   {  
     public static void Main(string[] args)  
      {  
       int  num, i;       
       int[] arr = new int[10];     
       Console.Write("Enter a number: ");    
       num = int.Parse(Console.ReadLine());     
       for(i=0; num>0; i++)      
        {      
         arr[i] = num%2;      
         num = num/2;    
        }      
       Console.Write("Binary conversion is: ");      
       for(i=i-1 ;i>=0 ;i--)      
       {      
        Console.Write(arr[i]);      
       }                 
      }  
  }

Output:

Explanation:

In the above example, we are converting a number from decimal to binary.