HforHisham
HforHisham

Reputation: 1974

Error in converting byte array to int array in C#

I am trying to convert a byte array to an int array ad then convert the byte array back to an int array.

For converting from byte array to int array I used this code:

int[] iArray = new int[someSize];
byte[] bArray = new byte[iArray.Length * sizeof(int)];
Buffer.BlockCopy(iArray, 0,bArray, 0, bArray.Length); // This code works correctly.

But when converting from the byte array to in int array, the values in the iArray2 array becomes false when the value in the iArray array is larger than 256 (may be it is overflow, I do not know.)

// What is the error in this code?.
int iArray2 = new int[someSize];
Buffer.BlockCopy(bArray, 0, iArray2, 0, iArray2.Length);

How can I convert from byte array to int array correctly?

Upvotes: 6

Views: 3597

Answers (1)

SLaks
SLaks

Reputation: 888273

Buffer.BlockCopy always deals in bytes, not array units.

Therefore, when you pass iArray2.Length in the second BlockCopy() call, you're copying that many bytes, which is one quarter of your actual array.

Upvotes: 7

Related Questions