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?
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
The easiest way to convert hexadecimal value to string is to use the fromhex() function. This function takes a hexadecimal value as a parameter and converts it into a string. The decode() function decodes bytearray and returns a string in utf-8 format.
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)
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With