字节数组到字节转换错误
Byte Array to Byte conversion error
我正在尝试翻转一个无符号 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 的那一行抱怨 "Cannot implicitly convert type 'byte[]' to '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.
我正在尝试翻转一个无符号 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 的那一行抱怨 "Cannot implicitly convert type 'byte[]' to '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.