Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a hex string as binary data in Python

Tags:

python

hex

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?

like image 445
mike_b Avatar asked Jul 23 '14 17:07

mike_b


People also ask

How do I encode strings to binary in Python?

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) .

How do you decode a hex string in Python?

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.


2 Answers

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)
like image 62
Justin R. Avatar answered Oct 07 '22 10:10

Justin R.


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'
like image 40
Youngmin Kim Avatar answered Oct 07 '22 11:10

Youngmin Kim