C# Binary Representation for Integer

Dot Net Perls
Bits represented as zeros

You want to see the binary representation of an int using the C# language. Integers have 32 bits and you want to see which ones are turned on, and which ones aren't. You want to see the sign bit. The method we show here is special in a couple ways: it has some performance improvements and has a simpler calling pattern.

Display 32 bits

Here we look a method that can display bits as zeros and ones from an integer. Every 32-bit integer can be converted into a text display of 32 zeros and ones with this method. I feel the algorithm is simpler than many others.

Program that shows binary representation [C#]

using System;

class Program
{
    static void Main()
    {
	// Write full binary string for 100.
	Console.WriteLine(GetIntBinaryString(100));

	// Write full binary string for 100000.
	Console.WriteLine(GetIntBinaryString(100000));
    }

    static string GetIntBinaryString(int n)
    {
	char[] b = new char[32];
	int pos = 31;
	int i = 0;

	while (i < 32)
	{
	    if ((n & (1 << i)) != 0)
	    {
		b[pos] = '1';
	    }
	    else
	    {
		b[pos] = '0';
	    }
	    pos--;
	    i++;
	}
	return new string(b);
    }
}

Output

00000000000000000000000001100100
00000000000000011000011010100000
Char type

Description. It receives a normal integer, and then loop each of the 32 bit positions. At the same time, it writes zeros and ones in reverse order. This results in standard results. The char array it uses is the most efficient structure here for the string we are creating. My research shows that this is much better than StringBuilder.

Char Array Use StringBuilder Secrets

Correctness. Methods that don't work are worse than useless. To test, I used an online tool from the City University of New York. Note that the tool has browser JavaScript problems and you need to keep refreshing it to make sure it works.

Reference page

Remove trailing zeros

This next method simply calls TrimStart on the resulting string. It provides output identical to the CUNY JavaScript tool. I haven't found this method as useful, because usually the trailing zeroes are useful.

TrimStart Method
Method that uses TrimStart [C#]

static string GetIntBinaryStringRemoveZeros(int n)
{
    char[] b = new char[32];
    int pos = 31;
    int i = 0;

    while (i < 32)
    {
	if ((n & (1 << i)) != 0)
	{
	    b[pos] = '1';
	}
	else
	{
	    b[pos] = '0';
	}
	pos--;
	i++;
    }
    return new string(b).TrimStart('0');
}

Summary

We looked at how you can display the 1s and 0s from an integer, using the C# language. This sort of debugging code can really solve hard problems when you are working on really complicated structures. The two functions here clearly display the left-most bit as the sign, and use character arrays which enhance performance.

And Bitwise Operator Shift Operators Bit Tips