Convert Decimal to Binary (base -2)

Question:

Write a C# program to convert any decimal number (base-10 (0 to 9)) into binary number (base-2 (0 or 1))?

Answer:

Decimal Number – Decimal number is a base 10 number because it ranges from 0 to 9, there are total 10 digits between 0 to 9. Any combination of digits is decimal number such as 223, 585, 192, 0, 7 etc.  

Binary Number – Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is binary number such as 1001, 101, 11111, 101010 etc.

Logic:

  • Divide the number by 2 through % (modulus operator) and store the remainder in array
  • Divide the number by 2 through / (division operator)
  • Repeat the step 2 until the number is greater than zero
static int[] GetBinaryNumber(int n)
{
    var cnt = 0;
    var result = new int[10];
 
    while (n > 0)
    {
        result[cnt] = n % 2;
        n /= 2;
        cnt++;
    }
   return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *