I need to convert binary 10100101
to an integer in C# without using Convert.ToInt64(bin,2), I'm working with the .net micro framework. When I use int i = Convert.ToInt32(byt, 2);
an exception is thrown with the rather unhelpfull message of:
#### Exception System.ArgumentException - 0x00000000 (1) ####
#### Message:
#### System.Convert::ToInt32 [IP: 000d] ####
#### TRNG.Program::loop [IP: 0047] ####
#### TRNG.Program::Main [IP: 0011] ####
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Slightly faster than Femaref's option, as it doesn't require a pesky method call, and uses OR instead of ADD just for fun:
public static int ParseBinary(string input)
{
// Count up instead of down - it doesn't matter which way you do it
int output = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '1')
{
output |= 1 << (input.Length - i - 1);
}
}
return output;
}
You may want to:
Just for LOLs, here's a LINQ version:
public static int ParseBinary(string input)
{
return input.Select((c, index) => new { c, index })
.Aggregate(0, (current, z) => current | (z.c - '0') <<
(input.Length - z.index - 1));
}
Or neater yet:
public static int ParseBinary(string input)
{
return return input.Aggregate(0, (current, c) => (current << 1) | (c - '0'));
}