Search code examples
c#memorybytearraysshort

Convert two bytes to Int16 in C#?


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?


Solution

  • 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.