Mark Galeck Mark Galeck - 3 years ago 258
Python Question

With Python 3, how to write() 8-bit unsigned integers with high bit 1, as 1 byte?

I am using

. I want to
all 8-bit unsigned integers as 1 byte to a subprocess - let me show you what I mean:

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

This is no good, I want to output 1 byte, not 2. I guess this is because the default encoding is utf-8. OK, I try

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

Certainly, no good either.

What do I put after
in order to send just 1 byte to the subprocess, for all unsigned integers from
, exactly 1 byte with bits just like the 8-bit representation of the integer?

Answer Source

You could use:

p = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
x = 0x80
p.stdin.write(bytearray.fromhex(format(x, 'x')))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download