Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert file to binary (make a hexdump)

Tags:

python

I want to display file that convert to binary like binary editer.

For example, it convert PNG to 89 50 4E 47 0D 0A 1A 0A 00 00 00....

f = open(path, "r")
print f.read() # I want to convert this to binary
f.close()

Please advice me.

like image 913
hucuhy Avatar asked Feb 13 '23 11:02

hucuhy


1 Answers

Python 3

To get a binary in a hex representation:

bin_data = open(path, 'rb').read()
import codecs
hex_data = codecs.encode(bin_data, "hex_codec")

If path refers to a PNG file, then the first few bytes of bin_data will look like \x89PNG\r\n and the beginning of hex_data will look like 89504e470d0a. To format it nicely, add spaces:

import re
hex_with_spaces =  re.sub('(..)', r'\1 ', hex_data)

The corresponding first few bytes of hex_with_spaces will look like 89 50 4e 47 0d 0a.

As an alternative to codecs, the binascii can be used:

import binascii
hex_data = binascii.hexlify(bin_data)

See jfs's answer for a more detailed example using binascii.

Python 2

To get a binary in a hex representation:

bin_data = open(path, 'rb').read()
hex_data = bin_data.encode('hex')

If path refers to a PNG file, then the first few bytes of bin_data will look like \x89PNG\r\n and the beginning of hex_data will look like 89504e470d0a. To format it nicely, add spaces:

import re
hex_with_spaces =  re.sub('(..)', r'\1 ', hex_data)

The corresponding first few bytes of hex_with_spaces will look like 89 50 4e 47 0d 0a.

like image 101
John1024 Avatar answered Feb 16 '23 02:02

John1024