bunbun
bunbun

Reputation: 2676

Create text file of hexadecimal from binary

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

Upvotes: 0

Views: 1497

Answers (3)

Eddmik
Eddmik

Reputation: 175

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

Upvotes: 0

jfs
jfs

Reputation: 414079

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

Upvotes: 0

Undeterminant
Undeterminant

Reputation: 1358

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.

Upvotes: 1

Related Questions