Byte array for int C #

I am triyng to convert a byte array to an int value however I get an exception:

"The target array is not long enough to copy all the elements into the collection. Check the index and length of the array.

the exception is in the line:

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

byte _length contains 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
source share
1 answer

Int3232 bits or four bytes are required. Your array contains only two bytes, which means you cannot convert it to Int32.

You can convert it to Int16

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

or expand two bytes to an array before conversion Int32.

Alternatively, you can skip copying altogether:

int length = BitConverter.ToInt16(data, Place_of_length);
+11
source

Source: https://habr.com/ru/post/1622346/


All Articles