Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert two bytes to Int16 in C#? [duplicate]

Possible Duplicates:
Good way to convert between short and bytes?
How can I combine 4 bytes into a 32 bit unsigned integer?

Alright , so I am developing this virtual machine and it has 64 kbs of memory. I am using a byte[] array for the memory and I have one problem. How would I convert 2 bytes to a short or 4 bytes to a Int32?

like image 562
Grunt Avatar asked Nov 29 '22 18:11

Grunt


1 Answers

Others suggested BitConverter.
Here is a different solution

Short:

var myShort = (short) (myByteArray[0] << 8 | myByteArray[1]);

Int32

var myint = myByteArray[0] << 24 | myByteArray[1] << 16 | myByteArray[2] << 8 | myByteArray[3];

Mind the endianness though.

like image 180
Sani Singh Huttunen Avatar answered Dec 01 '22 06:12

Sani Singh Huttunen