6

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?

1
  • 2
    A byte stores values from 0 to 255. What value would you expect the resulting byte to have when converted from an integer value of, say, 1000? Commented Apr 26, 2012 at 19:45

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@HeshamAbouelsoaod: By passing the correct length in bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.