Trivial: Binary To Integer

In response to a web-forum question, I found myself writing a little C# to convert from a string (containing a binary number) into the integer representation of the same. It’s the kind of trivial coding problem that first year programmers would come up against… Of course, we could make it harder by stipulating that we cannot use System.Convert.

I’m sure that there are much better ways of doing this, and I’d be glad to see some of them appear in the comments for this post. There, a kind of challenge…If the quality of the comments is good enough, I might be able to offer a small prize if you are a UK resident. No promises though!

[code lang=”C#”]
public int BinToInt(string binaryNumber)
int multiplier = 1;
int converted = 0;

for (int i = binaryNumber.Length – 1; i >= 0; i–)
int t = System.Convert.ToInt16(binaryNumber[i].ToString());
converted = converted + (t * multiplier);
multiplier = multiplier * 2;
return converted;

In use:

[code lang=”C#”]
// remember SEFTU, sixteen, eight, four, two, one
listBox1.Items.Add(BinToInt(“00001”).ToString()); // 1
listBox1.Items.Add(BinToInt(“00010”).ToString()); // 2
listBox1.Items.Add(BinToInt(“00011”).ToString()); // 3
listBox1.Items.Add(BinToInt(“00100”).ToString()); // 4
listBox1.Items.Add(BinToInt(“00101”).ToString()); // 5
listBox1.Items.Add(BinToInt(“00111”).ToString()); // 7
listBox1.Items.Add(BinToInt(“01000”).ToString()); // 8
listBox1.Items.Add(BinToInt(“10000”).ToString()); // 16[/code]

It might be of use to somebody…somewhere…