[英]Error when copying bytes - offset and length were out of bounds.
我试图将值的二维数组转换为 byte[] 并返回到原始的二维数组。 运行我的代码时出现此错误:
An unhandled exception of type 'System.ArgumentException' occurred in TestProject.exe.
Additional information: Offset and length were out of bounds
for the array or count is greater than the number of elements from the
index to the end of the source collection.
这是我的代码:
byte[,] dataArray = new byte[,] {
{4, 6, 2},
{0, 2, 0},
{1, 3, 4}
};
for (int j = 0; j < 3; j++)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Value[" + i + ", " + j + "] = " + dataArray[j, i]);
}
}
long byteCountArray = dataArray.GetLength(0) * dataArray.GetLength(1) * sizeof(byte);
var bufferByte = new byte[byteCountArray];
Buffer.BlockCopy(dataArray, 0, bufferByte, 0, bufferByte.Length);
//Here is where I try to convert the values and print them out to see if the values are still the same:
byte[] originalByteValues = new byte[bufferByte.Length / 2];
Buffer.BlockCopy(bufferByte, 0, originalByteValues, 0, bufferByte.Length);
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Values---: " + originalByteValues[i]);
}
错误发生在 Buffer.BlockCopy 行上:
Buffer.BlockCopy(bufferByte, 0, originalByteValues, 0, bufferByte.Length);
我是字节编程/转换的新手,因此感谢您提供任何帮助。
您使数组太小,是您尝试复制的大小的一半
new byte[bufferByte.Length / 2];
似乎应该是
new byte[bufferByte.Length];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.