C# – How to Convert BYTE Array to INT

arraysc++type-conversion

I have this kind of code

static void Main(string[] args)
{
     byte[] array = new byte[2] { 0x00, 0x1f };
     Console.WriteLine(BitConverter.ToInt32(array, 0));
}

However it does not work. It throws an exception:

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

What is wrong?

Best Answer

As the name suggests, an Int32 is 32 bits, or 4 bytes, so if you want to convert a byte array to an Int32, it needs to have a length of at least 4, (or more precisely, it needs to have least 4 bytes after the start position).

If all you have is two bytes, maybe you meant to use ToInt16?