22

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?

0

4 Answers 4

23

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?

Sign up to request clarification or add additional context in comments.

Comments

13

An Int32 is composed of 4 bytes but the array only has 2. One way to work around this is to first convert to Int16 and then to Int32

Console.WriteLine((Int32)(BitConverter.ToInt16(array, 0)));

Note that in this specific usage converting to Int32 from Int16 doesn't change anything because the numbers print the same.

2 Comments

Just as writing the decimal number "10" as "0010" doesn't change anything else either: the additional zeroes are meaningless, and you're more or less doing the same when you convert an Int16 to an Int32.
FYI, Visual Studio 2022 using .Net 6 says the Int32 conversion is redundant.
8

This is an old question, but for .NET Core / .NET Standard > 2.1 there is new solution:

The System.Buffers.Binary.BinaryPrimitives class provides two static methods ReadInt32BigEndian and ReadInt32LittleEndian for this purpose.

Using this these methods has two advantages:

  1. It lets you explicitly specify if your number is stored as little endian or big endian.
  2. They accept a Span<T> which can be a performance advantage, depending on the scenario.

Comments

4

The documentation on BitConverter.ToInt32 says:

The ToInt32 method converts the bytes from index startIndex to startIndex + 3 to an Int32 value.

You need to specify at least 4 bytes, but you only have 2.

Comments

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.