c# - 字节数组到字节转换错误

标签 c# bit-manipulation byte arrays implicit-conversion

我正在尝试翻转一个无符号 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[] 并且不知道为什么会抛出此错误。

最佳答案

result 已经是一个 byte[],所以改为这样做:

BitArray b = new BitArray(result);

实际导致问题的部分是:

new byte[] { result }

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

For a single-dimensional array, the array initializer must consist of a sequence of expressions that are assignment compatible with the element type of the array.

关于c# - 字节数组到字节转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28523047/

相关文章:

c - 算术右移后出现意外结果

java - 设置 int 的半字节 - java

ruby - 如何将 double 转换为十六进制?

c# - LINQ - 将属性添加到结果

c# - 基于 [Type] 对象转换和类型转换对象

c++ - "int mask = ~0;"的目的是什么?

java - Java中如何将十六进制字符串转换为字节数组

c# - 保留回发时在客户端设置的表格单元格背景颜色

c# - 如何四舍五入到特定的小数精度?

windows - 为什么 Windows 中的换行符是 2 个字节?