简体   繁体   English

如何在Python 3中将原始十六进制字节写入stdout?

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

How do you get Python 3 to output raw hexadecimal byte? 你如何让Python 3输出原始的十六进制字节? I want to output the hex 0xAA . 我想输出十六进制0xAA

If I use print(0xAA) , I get the ASCII '170'. 如果我使用print(0xAA) ,我会得到print(0xAA) '。

print() takes unicode text and encodes that to an encoding suitable for your terminal. print()接受unicode文本并将其编码为适合您的终端的编码。

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: 如果要编写原始字节,则必须写入sys.stdout.buffer以绕过io.TextIOBase并避免编码步骤,并使用bytes()对象从整数生成字节:

import sys

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

This won't include a newline (which is normally added when using print() ). 这不包括换行符(通常在使用print()时添加)。

The solution was to first create a bytes object: 解决方案是首先创建一个bytes对象:

x = bytes.fromhex('AA')

And then output this to stdout using the buffered writer 然后使用缓冲的writer将其输出到stdout

sys.stdout.buffer.write(x)

You can also use the hex-byte escape sequence ("\\x") in a bytestring, specifying the sys.stdout.buffer.write() method: 您还可以在bytestring中使用十六进制字节转义序列(“\\ x”),指定sys.stdout.buffer.write()方法:

$ 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 : 并使用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!....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM