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

前端 未结 3 1793
一整个雨季
一整个雨季 2020-12-09 22:39

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

3条回答
  •  既然无缘
    2020-12-09 23:20

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

提交回复
热议问题