mike_b
mike_b

Reputation: 2367

Write a hex string as binary data in Python

I have a string of data like FF0000FF and I want to write that to a file as raw 8-bit bytes 11111111 00000000 00000000 11111111. However, I seem to end up getting way to much data FF turns into FF 00 00 00 when using struct.pack or I get a literal ASCII version of the 0's and 1's.

How can I simply take a string of hex and write that as binary, so when viewed in a hex-editor, you see the same hex string?

Upvotes: 14

Views: 25077

Answers (3)

Youngmin Kim
Youngmin Kim

Reputation: 405

You could use bytes's hex and fromhex like this:

>>> ss = '7e7e303035f8350d013d0a'
>>> bytes.fromhex(ss)
b'~~005\xf85\r\x01=\n'
>>> bb = bytes.fromhex(ss)
>>> bytes.hex(bb)
'7e7e303035f8350d013d0a'

Upvotes: 3

Motorhead
Motorhead

Reputation: 968

In Python 3.x you can just use the b prefix in front of modified form of the string, and then write it out to a binary file like so:

hex_as_bytes = b"\xFF\x00\x00\xFF"
with open("myFileName", "wb") as f: f.write(hex_as_bytes)

Upvotes: 0

Justin R.
Justin R.

Reputation: 24021

You're looking for binascii.

binascii.unhexlify(hexstr)
Return the binary data represented by the hexadecimal string hexstr.
This function is the inverse of b2a_hex(). hexstr must contain
an even number of hexadecimal digits (which can be upper or lower
case), otherwise a TypeError is raised.

import binascii
hexstr = 'FF0000FF'
binstr = binascii.unhexlify(hexstr)

Upvotes: 19

Related Questions