# C# program to convert decimal to binary

19 Nov 2017

C# contains a robust way to convert int, long to its binary representation using `Convert.ToString(n, 2)`. It is more convenient to use & performant using native code implementation.

If you want an alternate way to do it through simple C# bit operation, then you can use the following suggested `ToBinary(n)` implementation. In most cases, this custom implementation is few ticks faster than the BCL implemenatation . May be not, share your views.

Source code provided below;

``````using System;

namespace CompProg.Algorithm.BIT
{
public class ConvertDecimal2Binary
{
static string ToBinaryBCL(int n) => Convert.ToString(n, 2);

static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];

if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}

for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}

return new string(output, 0, j);
}

static void Main(string[] args)
{
int[] test = { int.MaxValue, int.MaxValue - 1, 1000000, 8888, 88, 99, 1, -0, -1, -2, int.MinValue + 100000, int.MinValue + 100, int.MinValue + 1, int.MinValue };
foreach (var n in test)
{
Console.WriteLine("Calculate for i = " + n);
var watch = System.Diagnostics.Stopwatch.StartNew();
Console.WriteLine("BCL: " + ToBinaryBCL(n));
watch.Stop();

watch.Restart();
Console.WriteLine("Cus: " + ToBinary(n) + Environment.NewLine);
watch.Stop();
}

//// Unit Test
//for (int i = int.MaxValue, j; i >= 0; i--)
//{
//    j = -1 * i;
//    if (!ToBinary(i).Equals(ToBinaryBCL(i)))
//    {
//        Console.WriteLine("Failed at i = " + i);
//        break;
//    }
//    if (!ToBinary(j).Equals(ToBinaryBCL(j)))
//    {
//        Console.WriteLine("Failed at j = " + j);
//        break;
//    }
//}
}
}
}
``````