开发者

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

This question already has answers here: Closed 11 years ago.

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 probl开发者_JAVA百科em. How would I convert 2 bytes to a short or 4 bytes to a Int32?


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.


You can use BitConverter. If it's a virtual machine, you'll want to double check the expected endian-ness (in case it's reversed from your PC's endian-ness.)


// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);

Where bytes is your array of bytes that is to be converted.

Source: http://msdn.microsoft.com/en-us/library/bb384066.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜