Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in converting byte array to int array in C#

Tags:

c#

byte

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?

like image 794
HforHisham Avatar asked Apr 26 '12 19:04

HforHisham


1 Answers

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.

like image 110
SLaks Avatar answered Oct 03 '22 08:10

SLaks