Search code examples
c#arraysbitconverter

Byte array to int C#


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);

Solution

  • 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);