14

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?

2
  • Do you want to write out a string representation of the binary, or write out the actual numeric value? Commented Jul 23, 2014 at 17:13
  • I want to write out the binary representation of hex pairs as 8-bit values in binary format. Commented Jul 23, 2014 at 17:50

3 Answers 3

19

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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'

Comments

0

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)

1 Comment

sorry I omitted the hex escapes. I fixed it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.