How would I convert a file to a HEX string using Python? I have searched all over Google for this, but can't seem to find anything useful.
Asked
Active
Viewed 6.8k times
1 Answers
68
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
content = f.read()
print(binascii.hexlify(content))

Beat Bolli
- 421
- 2
- 10

unutbu
- 842,883
- 184
- 1,785
- 1,677
-
2will this convert png, jpg and other image format files? – anni Jul 25 '14 at 16:06
-
Yes, it opens the specified file of any type in binary format and the function just converts binary to hex format. – Deep LF Aug 23 '16 at 15:23
-
the hexdump prints the lines like "0000000 2123 7472 7070 616c 3179" where as the above code prints like "2321727470706c6179". Doe you see the bytes? they are flipped. 2123 is printed as 2321. Same 7472 as 7274. Why is so? – BTR Naidu Jan 18 '18 at 14:16
-
@BTRNaidu: Your machine uses [litte endian order](https://en.wikipedia.org/wiki/Endianness#Calculation_order): "This is the way a hexdump is displayed: because the dumping program is unable to know what kind of data it is dumping, the only orientation it can observe is monotonically increasing addresses. The human reader, however, who knows that he or she is reading a hexdump of a little-endian system ... reads the byte sequence 0Dh,0Ch,0Bh,0Ah as the 32-bit binary value 168496141, or 0x0a0b0c0d in hexadecimal notation." – unutbu Jan 18 '18 at 15:59
-
2On Ubuntu you can check your machine's endianness by running `lscpu`. To get hexdump output to match the output of the code above, run [`hexdump -C /path/to/file`](https://unix.stackexchange.com/a/55772/3330). – unutbu Jan 18 '18 at 16:06