Python 3:如何将附加到字节数组的数字附加为字节

时间:2017-03-28 11:38:14

标签: python byte

我想在Python脚本中做的是拥有一个bytearray并向其附加两个数字,将其作为消息发送,并让接收C应用程序再次读取该数字。

C app的内容如下:

//deserialize srvid from end of payload
UInt16 srvIdFrom;
UInt16 srvIdTo;

srvIdFrom = payload[len-4]  | payload[len-3] << 8;
srvIdTo = payload[len-2]  | payload[len-1] << 8;

我制作了一个Python脚本,试图像这样做:

my_bytes = bytearray()
numb = 1
dummySrvId = 1234
srvIdFrom = 5678
my_bytes.append(numb)
my_bytes.append(dummySrvId & 0xff)
my_bytes.append(dummySrvId >> 8)
my_bytes.append(srvIdFrom & 0xff)
my_bytes.append(srvIdFrom >> 8)

但它不起作用。 即,以下代码给出以下输出:

srvIdFrom = my_bytes[len(my_bytes)-4] << 8 | my_bytes[len(my_bytes)-3] << 0
srvIdTo = my_bytes[len(my_bytes)-2] << 8 | my_bytes[len(my_bytes)-1] << 0
print('return packet had srvIdFrom {} and srvIdTo {}'.format(srvIdFrom,srvIdTo))

输出

return packet had srvIdFrom 53764 and srvIdTo 44

或类似的东西。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您按以下顺序添加了字节

my_bytes.append(dummySrvId & 0xff)  # -4 (offset from end)
my_bytes.append(dummySrvId >> 8)    # -3
my_bytes.append(srvIdFrom & 0xff)   # -2
my_bytes.append(srvIdFrom >> 8)     # -1

但是在你的Python测试解码中,然后移动错误的字节,有效地交换MSB和LSB部分:

srvIdFrom = (
    my_bytes[len(my_bytes)-4] << 8   #  -4 is dummySrvId & 0xff
  | my_bytes[len(my_bytes)-3] << 0   #  -3 is srvIdFrom >> 8
)
srvIdTo = (
    my_bytes[len(my_bytes)-2] << 8   #  -2 is srvIdFrom & 0xff
  | my_bytes[len(my_bytes)-1] << 0   #  -1 is srvIdFrom >> 8
)

后者与您的C代码不匹配;你移动小端字节(偏移-3和-1):

srvIdFrom = payload[len-4]  | payload[len-3] << 8;
srvIdTo = payload[len-2]  | payload[len-1] << 8;

实际上,如果您交换移位并匹配C代码进行解码,则会得到正确的值:

>>> my_bytes[len(my_bytes)-4] | my_bytes[len(my_bytes)-3] << 8
1234
>>> my_bytes[len(my_bytes)-2] | my_bytes[len(my_bytes)-1] << 8
5678

所以其他错误。您的Python 编码工作正常。