Create text file of hexadecimal from binary

2019-09-02 16:05发布

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:

  1. This only prints the first byte.
  2. The result is "\x" and a box like this:

00 7f

In terminal it looks exactly like this: enter image description here

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

3条回答
爷的心禁止访问
2楼-- · 2019-09-02 16:14

Just add the content to list and print:

with open("default.png",'rb') as file_png:
    a = file_png.read()

l = []
l.append(a)
print l
查看更多
时光不老,我们不散
3楼-- · 2019-09-02 16:34

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:

from binascii import hexlify
with open('test', 'rb') as f:
  print(hexlify(f.read()).decode('utf-8'))

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.

查看更多
走好不送
4楼-- · 2019-09-02 16:36

Your output looks like a representation of a bytestring in Python returned by repr():

with open('input_file', 'rb') as file:
    print repr(file.read()) 

Note: some bytes are shown as ascii characters e.g. '\x52' == 'R'. If you want all bytes to be shown as the hex escapes:

with open('input_file', 'rb') as file:
    print "\\x" + "\\x".join([c.encode('hex') for c in file.read()])
查看更多
登录 后发表回答