Python binary conversion to hex

2019-02-26 23:57发布

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

I have tried both

repr(<mygzipfileobj>.getvalue())

as well as

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

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)

1条回答
Luminary・发光体
2楼-- · 2019-02-27 00:51

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.

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))
查看更多
登录 后发表回答