How to Convert Decimal to Binary in C#?
To convert a decimal number to binary, we use a simple below algorithm:
- Divide the decimal number by 2.
- Keep track of the remainder at each step.
- Continue dividing until the quotient is 0.
- Write the remainder in reverse order to get the binary equivalent.
C# program:
using System;
class DecimalToBinaryConverter
{
static void Main()
{
int decimalNumber = 15;
int[] binaryArray = new int[32];
int i = 0;
while (decimalNumber > 0)
{
binaryArray[i] = decimalNumber % 2;
decimalNumber = decimalNumber / 2;
i++;
}
Console.Write("Binary representation: ");
for (int j = i - 1; j >= 0; j--)
{
Console.Write(binaryArray[j]);
}
}
}
Output:
Binary representation: 1111
Comments (0)