简体   繁体   中英

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM