Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个二进制文件要读取,我想以正确的十六进制形式显示结果。代码如下:
file=open('myfile.chn', 'rb') while 1: b=fic.readline(1) print(b) file.close()
结果如下:
b'\xff' b'\xff' b'\x01' b'\x00' . .
我可以做些什么来改变结果如下:
FF FF 01 00 . .
"%02X" % ord(b'\xff')
将返回字符串'FF'。
'FF'
满足您保持前导零的要求:
>>> import binascii >>> binascii.hexlify(b'\x0f').decode().upper() '0F'
也适用于连续多个字节:
>>> binascii.hexlify(b'\xff\x01\x00\xaf').decode().upper() 'FF0100AF'