Skip to main content
 首页 » 编程设计

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

2024年02月06日10jyk

我正在尝试翻转一个无符号 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.