Error when copying bytes - offset and length were out of bounds.

14,737

you are making the array too small, half the size you are trying to copy

new byte[bufferByte.Length / 2];

seems it should be

new byte[bufferByte.Length];
Share:
14,737
Roka545
Author by

Roka545

Updated on June 04, 2022

Comments

  • Roka545
    Roka545 almost 2 years

    I've trying to convert a 2D array of values to a byte[] and back into the original 2D array. When running my code I get this error:

    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.
    

    Here's my code:

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

    The error occurs on the Buffer.BlockCopy line:

    Buffer.BlockCopy(bufferByte, 0, originalByteValues, 0, bufferByte.Length);
    

    I'm new to programming/conversion with bytes, so any help is appreciated.