freshnewpage
freshnewpage

Reputation: 443

How to write a raw hex byte to stdout in Python 3?

How do you get Python 3 to output raw hexadecimal byte? I want to output the hex 0xAA.

If I use print(0xAA), I get the ASCII '170'.

Upvotes: 14

Views: 34089

Answers (3)

TobalJackson
TobalJackson

Reputation: 139

You can also use the hex-byte escape sequence ("\x") in a bytestring, specifying the sys.stdout.buffer.write() method:

$ python -c 'import sys; sys.stdout.buffer.write(b"\x74\x68\x65\x73\x65\x20\x61\x72\x65\x20\x72\x61\x77\x20\x62\x79\x74\x65\x73\x21\xde\xad\xbe\xef")'

will output on your terminal:

these are raw bytes!ޭ��%

and inspecting with xxd:

$ python -c 'import sys; sys.stdout.buffer.write(b"\x74\x68\x65\x73\x65\x20\x61\x72\x65\x20\x72\x61\x77\x20\x62\x79\x74\x65\x73\x21\xde\xad\xbe\xef")' | xxd
00000000: 7468 6573 6520 6172 6520 7261 7720 6279  these are raw by
00000010: 7465 7321 dead beef                      tes!....

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1124658

print() takes unicode text and encodes that to an encoding suitable for your terminal.

If you want to write raw bytes, you'll have to write to sys.stdout.buffer to bypass the io.TextIOBase class and avoid the encoding step, and use a bytes() object to produce bytes from integers:

import sys

sys.stdout.buffer.write(bytes([0xAA]))

This won't include a newline (which is normally added when using print()).

Upvotes: 20

freshnewpage
freshnewpage

Reputation: 443

The solution was to first create a bytes object:

x = bytes.fromhex('AA')

And then output this to stdout using the buffered writer

sys.stdout.buffer.write(x)

Upvotes: 8

Related Questions