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

python3
. I want to
write()
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)))
2


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
p.stdin
in order to send just 1 byte to the subprocess, for all unsigned integers from
'\x00'
to
'\xff'
, 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