简体   繁体   English

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

[英]Python 3: how to append number appended to a byte array as bytes

What I'd want to do in a Python script is have a bytearray and append two numbers to it, send it as a message, and have the receiving C application can read the number again. 我想要在Python脚本中执行的操作是有一个字节数组,并向其附加两个数字,将其作为消息发送,并使接收C的应用程序可以再次读取该数字。

The C app reads like this: C应用程序的内容如下:

//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;

And I made a Python script that tries to do the above like this: 我制作了一个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)

but it does not work. 但它不起作用。 Ie, the following code gives the following output: 即,以下代码给出以下输出:

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

Output 产量

return packet had srvIdFrom 53764 and srvIdTo 44

Or stuff similar to that. 或类似的东西。 What am I doing wrong? 我究竟做错了什么?

You appended the bytes in the following order 您按以下顺序附加了字节

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

but in your Python test to decode, you then shift the wrong bytes , effectively swapping the MSB and LSB parts: 但是在您进行解码的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
)

The latter does not match your C code either; 后者也不匹配您的C代码。 you shift the little-endian bytes (offsets -3 and -1): 您将little-endian字节移位(偏移量-3和-1):

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

and indeed, if you swap the shifting and match your C code to decode, you get the correct values: 实际上,如果交换移位并匹配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

so something else is wrong . 所以还有其他问题 Your Python encoding work is fine. 您的Python 编码工作很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM