Byte array to int C#
Asked Answered
D

1

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);
Deuteron answered 31/12, 2015 at 14:11 Comment(4)
This code sample does not appear to be complete. Critically, we can't see where Value_of_length comes from.Eugeneeugenia
As you can tell, ToInt32() requires an array with at least 4 bytes. You have only 2, you could at best call ToInt16().Cheap
Int32 is so called because has 32 bits (4 bytes long)Glandular
int length = (int)BitConverter.ToInt16(bytes_length, 0);Kristofor
V
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);
Vet answered 31/12, 2015 at 14:16 Comment(2)
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);.Brindisi
@Brindisi Yes, that's right! Thank you!Vet

© 2022 - 2024 — McMap. All rights reserved.