代码之家  ›  专栏  ›  技术社区  ›  UnkwnTech

不使用Convert.ToInt32将二进制文件转换为int文件

  •  0
  • UnkwnTech  · 技术社区  · 14 年前

    我需要转换二进制 10100101 在不使用Convert.ToInt64(bin,2)的情况下,我使用的是.net micro框架。当我使用 int i = Convert.ToInt32(byt, 2); 引发异常,并显示以下消息:

     #### 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
    
    2 回复  |  直到 14 年前
        1
  •  4
  •   Jon Skeet    14 年前

    略快于Femaref的选项,因为它不需要烦人的方法调用,使用或代替ADD只是为了好玩:

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

    您可能需要:

    • 检查长度是否小于32
    • 检查每个字符是否为“0”或“1”

    只是为了LOLs,这里有一个LINQ版本:

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

    或者更整洁:

    public static int ParseBinary(string input)
    {
        return return input.Aggregate(0, (current, c) => (current << 1) | (c - '0'));
    }
    
        2
  •  1
  •   Femaref    14 年前
    string input = "10101001";
    int output = 0;
    for(int i = 7; i >= 0; i--)
    {
      if(input[7-i] == '1')
        output += Math.Pow(2, i);
    }
    

    一般来说:

    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);
    }
    
    推荐文章