Skip to content Skip to sidebar Skip to footer

Writing Hex Data Into A File

I'm trying to write hex data taken from ascii file to a newly created binary file ascii file example: 98 af b7 93 bb 03 bf 8e ae 16 bf 2e 52 43 8b df 4f 4e 5a e4 26 3f ca f7 b1 ab

Solution 1:

Use binascii.unhexlify:

>>>import binascii>>>binascii.unhexlify('9f')
'\x9f'

>>>hex(int('9f', 16))
'0x9f'

import binascii

withopen('hexFile.txt') as f, open('test', 'wb') as fout:
    for line in f:
        fout.write(
            binascii.unhexlify(''.join(line.split()))
        )

Solution 2:

replace:

    f.write(hex(i))

With:

    f.write(chr(i))  # python 2

Or,

    f.write(bytes((i,))) # python 3

Explanation

Observe:

>>> hex(65)
'0x41'

65 should translate into a single byte but hex returns a four character string. write will send all four characters to the file.

By contrast, in python2:

>>> chr(65)
'A'

This does what you want: chr converts the number 65 to the character single-byte string which is what belongs in a binary file.

In python3, chr(i) is replaced by bytes((i,)).

Post a Comment for "Writing Hex Data Into A File"