Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting BYTE array to INT

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?

like image 992
user1317200 Avatar asked Feb 07 '14 23:02

user1317200


People also ask

Can you convert a byte to an int?

To convert bytes to int in Python, use the int. from_bytes() method. A byte value can be interchanged to an int value using the int.

What is byte array in C#?

In C#.Net, we can create an unsigned byte array by using byte, byte is used to store only positive values between the range of 0 to 255 (Unsigned 8 bits integer). It occupies 1-byte memory for each element, if array size is 10, it will take 10 bytes memory.

What is byte array format?

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.


3 Answers

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?

like image 93
p.s.w.g Avatar answered Oct 19 '22 13:10

p.s.w.g


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.

like image 10
JaredPar Avatar answered Oct 19 '22 11:10

JaredPar


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.

like image 4
Grant Winney Avatar answered Oct 19 '22 13:10

Grant Winney