简体   繁体   English

字节数组到字节的转换错误

[英]Byte Array to Byte conversion error

I am trying to flip the bits of an unsigned 32-bit integer and output the resultant integer. 我正在尝试翻转无符号32位整数的位并输出结果整数。 The following is my code. 以下是我的代码。

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

However, the compiler complains that "Cannot implicitly convert type 'byte[]' to 'byte' " on the line where I declare BitArray b. 但是,编译器抱怨在我声明BitArray b的行上“无法将类型'byte []'隐式转换为'byte'”。 I have declared it as a byte[] and have no idea why this error is being thrown. 我已将其声明为byte [],并且不知道为什么会引发此错误。

result is already a byte[] , so do this instead: result已经是一个byte[] ,所以可以这样做:

BitArray b = new BitArray(result);

The part that's actually causing the problem is this: 真正引起问题的部分是这样的:

new byte[] { result }

The reason for this is because the array initializer needs to take expressions that are compatible with the element type of the array (here, byte ). 这样做的原因是因为数组初始化器需要采用与数组元素类型(此处为byte )兼容的表达式。 From 12.6 Array Initializers : 12.6数组初始化程序开始

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. 对于一维数组,数组初始化器必须由一系列表达式组成,这些表达式的分配与数组的元素类型兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM