I am using BitConverter.ToInt32 to convert a Byte array into int.
I have only two bytes [0][26], but the function needs 4 bytes, so I have to add two 0 bytes to the
You should probably do (int)BitConverter.ToInt16(..)
instead. ToInt16
is made to read two bytes into a short
. Then you simply convert that to an int
with the cast.
Array.Copy
. Here is some code:
byte[] arr = new byte[] { 0x12, 0x34 };
byte[] done = new byte[4];
Array.Copy(arr, 0, done, 2, 2); // http://msdn.microsoft.com/en-us/library/z50k9bft.aspx
int myInt = BitConverter.ToInt32(done); // 0x00000026
However, a call to `BitConverter.ToInt16(byte[]) seems like a better idea, then just save it to an int:
int myInt = BitConverter.ToInt16(...);
Keep in mind endianess however. On little endian machines, { 0x00 0x02 }
is actually 512, not 2 (0x0002
is still 2, regardless of endianness).
You should call `BitConverter.ToInt16, which only reads two bytes.
short
is implicitly convertible to int
.