尝试将uint16打包成字节数组C#的2个字节

时间:2013-12-11 20:11:14

标签: c# networking byte bytearray

我必须发送一个包结构为:

的数据包
1 byte padding (0x0)
2 byte (uint16) opcode
1 byte padding (0x0)
x bytes raw struct

所以我需要一种方法将uint16放入我的字节数组中。

byte[] rawData = new byte[x+4];
rawData[0] = 0;
rawData[1] = (uint16-highbyte?) opcode;
rawData[2] = (uint16-lowbyte?) opcode;

3 个答案:

答案 0 :(得分:2)

rawData[1] = (byte) (opcode >> 8);
rawData[2] = (byte) opcode;

>>是签名的右移运营商。它会向右移位,重复左边最左边的位,以保持带符号的双补码数有效。

例如:

+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |  = 0x0301
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

0x0301 >> 8 =

+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |  = 0x0003
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

(byte)强制转换只会保留数据的低8位。所以:

                                +---+---+---+---+---+---+---+---+
(byte) (0x0301 >> 8) =          | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |  = 0x03
                                +---+---+---+---+---+---+---+---+

                                +---+---+---+---+---+---+---+---+
(byte) 0x0301 =                 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |  = 0x01
                                +---+---+---+---+---+---+---+---+

答案 1 :(得分:0)

这是另一种方法。

fixed(short* ps = &rawData[1]){
    *ps = opcode;
}

好运!

<强>更新

这两者都会产生相同的结果。

byte[] rawData = new byte[4];
short opcode = 16859;

fixed (void* ps = &rawData[1]) {
    *(short*)ps = opcode;
}

Console.WriteLine(BitConverter.ToInt32(rawData, 0));

byte[] opBytes = BitConverter.GetBytes(opcode);

rawData = new byte[4];
rawData[1] = opBytes[0];
rawData[2] = opBytes[1];

Console.WriteLine(BitConverter.ToInt32(rawData, 0));

答案 2 :(得分:-1)

C#已经有了这样做的事情......

BitConverter.GetBytes(opcode);

此处记录: -

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