Converting a binary string to an int in C#
Back in my previous post, Converting an int to a binary string, we looked at how to write out the bits of an int
without using the existing Convert.ToString
method in the .NET Framework. Now, let’s look at the reverse – how to convert that binary string back into an int
. The .NET Framework already has a built in method to do this (obviously), which is the Convert.ToInt32(string, int)
method. This method takes the binary string and the base to convert from as parameters.
The easiest way that I have found to convert a binary number to decimal is to look at the bits of the binary number and raise 2 to the power of the index of the “on” bits and add those together. I define an “on” bit as a bit that is 1 as opposed to 0.
For example, the binary number 100
can be looked at as
22 + 0 + 0 = 4
Similary, 101
can be looked at as
22 + 0 + 20 = 5
Knowing this, we can then loop through the characters of the binary string, check if the bit is “on” and, if so, add
2 [index]
to resulting int
. In the code example below, I first reverse the array to allow the index of our loop (power
) match up with the index of the binary string (the power in which we want to raise 2 to).
public static int BitStringToInt(string bits)
{
var reversedBits = bits.Reverse().ToArray();
var num = 0;
for (var power = 0; power < reversedBits.Count(); power++)
{
var currentBit = reversedBits[power];
if (currentBit == '1')
{
var currentNum = (int) Math.Pow(2, power);
num += currentNum;
}
}
return num;
}