【问题标题】:Byte Array to Byte conversion error字节数组到字节转换错误
【发布时间】:2015-02-15 04:39:12
【问题描述】:

我正在尝试翻转无符号 32 位整数的位并输出结果整数。以下是我的代码。

int numberOfTries = Convert.ToInt32(Console.ReadLine());
        for (int i = 0; i < numberOfTries; i++)
        {
            uint input = Convert.ToUInt32(Console.ReadLine());
            byte[] bInput = BitConverter.GetBytes(input);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bInput);
            byte[] result = bInput;

            BitArray b = new BitArray(new byte[] { result });
            b.Not();
            uint res = 0;
            for (int i2 = 0; i2 != 32; i2++)
            {
                if (b[i2])
                {
                    res |= (uint)(1 << i2);
                }
            }

            Console.WriteLine(res);
        }

但是,编译器在我声明 BitArray b 的那一行抱怨“无法将类型 'byte[]' 隐式转换为 'byte'”。我已将其声明为 byte[] 并且不知道为什么会引发此错误。

【问题讨论】:

    标签: c# bit-manipulation byte bytearray implicit-conversion


    【解决方案1】:

    result 已经是byte[],所以改为:

    BitArray b = new BitArray(result);
    

    实际上导致问题的部分是:

    new byte[] { result }
    

    这样做的原因是因为数组初始值设定项需要采用与数组元素类型兼容的表达式(此处为byte)。来自12.6 Array Initializers

    对于一维数组,数组初始值设定项必须由一系列与数组元素类型赋值兼容的表达式组成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-07
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 2011-07-02
      • 2019-12-10
      • 1970-01-01
      相关资源
      最近更新 更多