Writing bytes to a data array (C#)

Let's say there is an array of data, there was some mathematical operation on these bytes and we need to save the result in another array, also consisting of bytes. I do this in a loop.

public static byte[] bitData;
public static byte[] testData = { };

// Математические операции

for (int i = 0; i < bitData.Length; i++) {
 testData[i] = (byte)(bitData[i]);
}

When executing this code, an error occurs: "The index was outside the bounds of the array." Tell me how to solve this problem, so that you can write these results as bytes to another variable. Thanks!

 1
Author: A K, 2018-10-29

2 answers

Arrays in C# do not support changing the capacity.

Line

byte[] testData = { };

The compiler expands to

byte[] testData = new byte[0];

I.e. it creates an array with a capacity of 0 elements.

You have at least 2 solutions:

  • You can create an array of the desired capacity before filling it

    testData = new byte[bitData.Length];
    for (int i = 0; i < bitData.Length; i++) {
        testData[i] = bitData[i];
    }
    
  • Or use a ready-made collection that supports dynamic modification capacity

    var testData = new List<byte>();
    for (int i = 0; i < bitData.Length; i++) {
        testData.Add(bitData[i]);
    }
    

Note that the Add method is used here, which first increases the capacity of the collection, and then adds the specified value to the last element. Using the indexer will throw the same exception as you get.

 1
Author: Андрей NOP, 2018-10-29 12:31:52

Why do you cast byte to byte (byte)(BitData[i]);?
On business:
To copy data from an array to an array, use (usually) the Array class and the Copy method:

byte[] array = {1,2};
byte[] newArray = new byte[array.Length];

Array.Copy(array, newArray, array.Length);
 0
Author: LiptonDev, 2018-10-29 12:00:09