Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 499
Barak Rosenfeld Avatar asked Dec 31 '15 14:12

Barak Rosenfeld


People also ask

What is byte array in C?

byte array in CAn unsigned char can contain a value from 0 to 255, which is the value of a byte. In this example, we are declaring 3 arrays – arr1, arr2, and arr3, arr1 is initialising with decimal elements, arr2 is initialising with octal numbers and arr3 is initialising with hexadecimal numbers.

Can we assign byte to int?

A bytes object can be converted to an integer value easily using Python. Python provides us various in-built methds like from_bytes() as well as classes to carry out this interconversion.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

What is byte array?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..


1 Answers

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);
like image 103
Sergey Kalinichenko Avatar answered Sep 22 '22 11:09

Sergey Kalinichenko