[英]Python struct.pack dropping a byte.
If I run the following using Python 3.3.1: 如果我使用Python 3.3.1运行以下命令:
import struct
struct.pack('!Bhh', 1, 1, 10)
I get this result: 我得到这个结果:
b'\x01\x00\x01\x00\n'
rather than the result I am expecting: 而不是我期望的结果:
b'\x01\x00\x01\x00\x0a\n'
Can anyone tell me where my missing byte has gone? 谁能告诉我丢失的字节在哪里?
Your lost byte is right there; 您丢失的字节就在那里;
\\n
is character 10 in the ASCII table: \\n
是ASCII表中的字符10:
>>> chr(10)
'\n'
Instead of displaying it as \\x0a
it is displayed as a Python string literal escape code; 而不是将其显示为
\\x0a
,而是显示为Python字符串文字转义码; other known escapes are also shown that way. 其他已知的逃生路线也以这种方式显示。 Printable ASCII characters are shown as characters:
可打印的ASCII字符显示为以下字符:
>>> struct.pack('!Bhh', 1, 1, 13)
b'\x01\x00\x01\x00\r'
>>> struct.pack('!Bhh', 1, 1, 9)
b'\x01\x00\x01\x00\t'
>>> struct.pack('!Bhh', 1, 1, 65)
b'\x01\x00\x01\x00A'
It might help to use binascii.hexlify()
to convert your bytes to hexadecimal characters: 使用
binascii.hexlify()
将字节转换为十六进制字符可能会有所帮助:
>>> from binascii import hexlify
>>> hexlify(struct.pack('!Bhh', 1, 1, 10))
b'010001000a'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.