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.
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With