Converting an int to a binary string in C#
The .NET Framework has a built in overload of Convert.ToString
which takes 2 parameters: the int
you want to convert and an int
of the base you want to convert to. Utilizing this with base 2, you can print out the string representation of a number in binary, like so:
var binary = Convert.ToString(5, 2); //Gives you "101"
Now this is all fine and dandy, but you didn’t learn anything. (Or maybe you did. I don’t know. But you can learn some more so keep reading). For fun, let’s pretend that .NET didn’t have this method built in. How would you convert your number to it’s binary representation?
We can use a combination of bit shifting and logical AND’s to achieve this. If you logical AND a number with 1, that will give the value 1 or 0 depending on the value of the bit in the first position:
1101
& 0001 (The number 1 in binary)
------
0001
As we bit shift, 0’s are brought in from the left and the rightmost bit is dropped off and lost. If we bit shift the number to the right and then AND it with 1 again, we’ll get the result of the second bit.
0110
& 0001
------
0000
If we loop and continue to bit shift until the number is 0 we can build the entire binary string.
Example: Say we have the number 9, which in binary is 1001
. Here’s the breakdown:
Number | In Binary | AND Result | String |
---|---|---|---|
9 | 1001 | 1 | 1 |
4 | 0100 | 0 | 01 |
2 | 0010 | 0 | 001 |
1 | 0001 | 1 | 1001 |
0 | 0000 | N/A (number is 0 so we’re done!) | 1001 |
public string IntToBinaryString(int number)
{
const int mask = 1;
var binary = string.Empty;
while(number > 0)
{
// Logical AND the number and prepend it to the result string
binary = (number & mask) + binary;
number = number >> 1;
}
return binary;
}
If you would like to print the string with a specific bit length, you can use the PadLeft
method in the .NET Framework. it will prepend the specified number of a character of your choosing to your string:
binary = "1001";
binary = binary.PadLeft(8, '0');
// binary is now "00001001";