I would like to convert a binary to hexadecimal in a certain format and save it as a text file.
The end product should be something like this:
"\x7f\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52"
Input is from an executable file "a". This is my current code:
with open('a', 'rb') as f:
byte = f.read(1)
hexbyte = '\\x%02s' % byte
print hexbyte
A few issues with this:
- This only prints the first byte.
- The result is "\x" and a box like this:
00
7f
In terminal it looks exactly like this:
Why is this so? And finally, how do I save all the hexadecimals to a text file to get the end product shown above?
EDIT: Able to save the file as text with
txt = open('out.txt', 'w')
print >> txt, hexbyte
txt.close()
Just add the content to
list
andprint
:You can't inject numbers into escape sequences like that. Escape sequences are essentially constants, so, they can't have dynamic parts.
There's already a module for this, anyway:
Just use the hexlify function on a byte string and it'll give you a hex byte string. You need the
decode
to convert it back into an ordinary string.Not quite sure if
decode
works in Python 2, but you really should be using Python 3, anyway.Your output looks like a representation of a bytestring in Python returned by
repr()
:Note: some bytes are shown as ascii characters e.g.
'\x52' == 'R'
. If you want all bytes to be shown as the hex escapes: