Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.

like image 947
freshnewpage Avatar asked Aug 10 '15 10:08

freshnewpage


2 Answers

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

like image 101
Martijn Pieters Avatar answered Nov 06 '22 14:11

Martijn Pieters


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)
like image 5
freshnewpage Avatar answered Nov 06 '22 12:11

freshnewpage