Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having an issue to convert decimal to hex [duplicate]

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)

like image 982
codeJack Avatar asked Nov 17 '22 16:11

codeJack


1 Answers

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))
like image 200
Martijn Pieters Avatar answered Dec 05 '22 10:12

Martijn Pieters