Python to hex binary conversion

I am trying to convert a binary file that I have in python (a gzipped protocol buffer object) to an escape-style hexadecimal string (e.g. \ xFA \ x1C ..).

I tried both

repr(<mygzipfileobj>.getvalue()) 

and

 <mygzipfileobj>.getvalue().encode('string-escape') 

In both cases, I get a string that does not consist only of HEX characters.

 \x86\xe3$T]\x0fPE\x1c\xaa\x1c8d\xb7\x9e\x127\xcd\x1a.\x88v ... 

How can I achieve a consistent hexadecimal conversion where each individual byte is actually converted to \ xHH format? (where H represents a valid hex char 0-9A-F)

+1
source share
1 answer

The \xhh format that you often see is a debugging aid, the repr() output, applied to a string with non-ASCII code points. Any ASCII code points remain in place to leave readable information.

If you must have a line with all characters replaced by \xhh escapes, you need to do this manually:

 ''.join(r'\x{0:02x}'.format(ord(c)) for c in value) 

If you need quotes around this, you also need to add them manually:

 "'{0}'".format(''.join(r'\x{:02x}'.format(ord(c)) for c in value)) 
+2
source

Source: https://habr.com/ru/post/1276160/


All Articles