fre*_*age 5 python hex python-3.x
你如何让Python 3输出原始的十六进制字节?我想输出十六进制0xAA.
如果我使用print(0xAA),我得到ASCII'170'.
Mar*_*ers 11
print()获取unicode文本并将其编码为适合您的终端的编码.
如果要编写原始字节,则必须写入以sys.stdout.buffer绕过io.TextIOBase该类并避免编码步骤,并使用bytes()对象从整数生成字节:
import sys
sys.stdout.buffer.write(bytes([0xAA]))
Run Code Online (Sandbox Code Playgroud)
这不包括换行符(通常在使用时添加print()).
解决方案是首先创建一个bytes对象:
x = bytes.fromhex('AA')
Run Code Online (Sandbox Code Playgroud)
然后将其输出到stdout使用缓冲写入器
sys.stdout.buffer.write(x)
Run Code Online (Sandbox Code Playgroud)