Question

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
Was it helpful?

Solution

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:

  • Check that the length is less than 32 to start with
  • Check that every character is '0' or '1'

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'));
}

OTHER TIPS

string input = "10101001";
int output = 0;
for(int i = 7; i >= 0; i--)
{
  if(input[7-i] == '1')
    output += Math.Pow(2, i);
}

in general:

string input = "10101001";
int output = 0;
for(int i = (input.Length - 1); i >= 0; i--)
{
  if(input[input.Length - i] == '1')
    output += Math.Pow(2, i);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top