5

I am triyng to convert byte array into an int value however I am getting an exception:

"Destination array is not long enough to copy all the items in the collection. Check array index and length."

the exception is on line:

int length = BitConverter.ToInt32(bytes_length, 0);

byte _length contain the value (0x00,0x09);

here is my code:

byte[] bytes_length = new byte[Value_of_length];                   
//copy the byte byte array to the correct length.
Array.Copy(data, Place_of_length, bytes_length, 0,bytes_length.Length
int length = BitConverter.ToInt32(bytes_length, 0);
4
  • This code sample does not appear to be complete. Critically, we can't see where Value_of_length comes from. Commented Dec 31, 2015 at 14:15
  • 1
    As you can tell, ToInt32() requires an array with at least 4 bytes. You have only 2, you could at best call ToInt16(). Commented Dec 31, 2015 at 14:15
  • Int32 is so called because has 32 bits (4 bytes long) Commented Dec 31, 2015 at 14:16
  • int length = (int)BitConverter.ToInt16(bytes_length, 0); Commented Dec 31, 2015 at 15:18

1 Answer 1

14

Int32 needs 32 bits, or four bytes. Your array contains only two bytes, which means that you cannot convert it to Int32.

You can either convert it to Int16

int length = BitConverter.ToInt16(bytes_length, 0);

or to extend two more bytes to the array before Int32 conversion.

Moreover, you can skip copying altogether:

int length = BitConverter.ToInt16(data, Place_of_length);
Sign up to request clarification or add additional context in comments.

2 Comments

And, of course, once this is corrected, there's no need for the array copying steps that come before either. It should just be int length = BitConverter.ToInt16(data,Place_of_length);.
@Damien_The_Unbeliever Yes, that's right! Thank you!

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.