c# - 复制字节时出错 - 偏移量和长度超出范围。

标签 c# arrays type-conversion byte buffer

我试图将二维值数组转换为 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];

关于c# - 复制字节时出错 - 偏移量和长度超出范围。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693352/

相关文章:

c# - ServiceStack - 验证和数据库访问

c# - 在 C# 中,finally block 之前有一个 catch-all catch block 有什么用?

php - 通过PowerShell从JSON数组中提取特定对象作为逗号分隔的字符串

C: 声明一个指向常量字符数组的常量指针

vba - 寻找返回 Integer 的 WorksheetFunction 方法

c++ - 将 uint32 读取为没有溢出的 float ?

c# - 调试 Task.WhenAny 和推送通知

c++ - 左值需要作为赋值 C++ 数组的左操作数

c# - C# 中从文件中读取字节 block 并转换为 float[] 的最快方法

c# - 集合上的清除方法是否会释放事件订阅?