使用 Python 3,如何将高位 1 的 8 位无符号整数写为 1 个字节?



我正在使用python3. 我想将所有 8 位无符号整数write()为 1 字节到子进程 - 让我向您展示我的意思:

>>> p = subprocess.Popen(["./some_program"], stdin=subprocess.PIPE)
>>> x=0x80
>>> p.stdin.write(str.encode(chr(x)))
2

这不好,我想输出 1 个字节,而不是 2 个字节。 我想这是因为默认编码是 utf-8。 好的,我试试

>>> p.stdin.write(str.encode(chr(x), "ascii"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character 'x80' in position 0: ordinal not in range(128)

当然,也不行。

为了只向子进程发送 1 个字节,对于从'x00''xff'的所有无符号整数,我应该在p.stdin之后放什么,正好是 1 个字节,就像整数的 8 位表示一样?

您可以使用:

p = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
x = 0x80
p.stdin.write(bytearray.fromhex(format(x, 'x')))

避免双重转换的更好方法是:

p = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
x = [ 0x80 ]
p.stdin.write(bytearray(x)) 

最新更新