开发者

Convert Binary to int without Convert.ToInt32

开发者 https://www.devze.com 2023-01-27 04:58 出处:网络
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 thro

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开发者_C百科: 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:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号