Python二进制转换为十六进制 [英] Python binary conversion to hex
问题描述
我正在尝试以字符串转义方式(例如\ xFA \ x1C ..)将python中的二进制文件(压缩的协议缓冲区对象)转换为十六进制字符串.
I'm trying to convert a binary I have in python (a gzipped protocol buffer object) to an hexadecimal string in a string escape fashion (eg. \xFA\x1C ..).
我都尝试过
repr(<mygzipfileobj>.getvalue())
以及
<mygzipfileobj>.getvalue().encode('string-escape')
在两种情况下,我最终得到的字符串都不是仅由十六进制字符组成.
In both cases I end up with a string which is not made of HEX chars only.
\x86\xe3$T]\x0fPE\x1c\xaa\x1c8d\xb7\x9e\x127\xcd\x1a.\x88v ...
在每个单个字节实际上都转换为\ xHH格式的情况下,如何实现一致的十六进制转换? (其中H代表有效的十六进制字符0-9A-F)
How can I achieve a consistent hexadecimal conversion where every single byte is actually translated to a \xHH format ? (where H represents a valid hex char 0-9A-F)
推荐答案
您经常看到的\xhh
格式是调试辅助,repr()
的输出应用于非-ASCII码点.任何ASCII码点都保留在原处,以保留所有可读信息.
The \xhh
format you often see is a debugging aid, the output of the repr()
applied to a string with non-ASCII codepoints. Any ASCII codepoints are left a in-place to leave what readable information is there.
如果必须用\xhh
转义符替换所有所有字符的字符串,则需要手动进行:
If you must have a string with all characters replaced by \xhh
escapes, you need to do so manually:
''.join(r'\x{0:02x}'.format(ord(c)) for c in value)
如果您需要引号,也需要手动添加引号:
If you need quotes around that, you'd need to add those manually too:
"'{0}'".format(''.join(r'\x{:02x}'.format(ord(c)) for c in value))
这篇关于Python二进制转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!