gpt4 book ai didi

c# - 试图将 uint16 打包成字节数组 C# 的 2 个字节

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:02 25 4
gpt4 key购买 nike

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

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;

最佳答案

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
+---+---+---+---+---+---+---+---+

关于c# - 试图将 uint16 打包成字节数组 C# 的 2 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com