Reputation: 353
I'm trying to decode hex string to binary values. I found this below command on internet to get it done,
string_bin = string_1.decode('hex')
but I got error saying
'str' object has no attrubute 'decode'
I'm using python v3.4.1
Upvotes: 13
Views: 42778
Reputation: 1124758
You cannot decode string objects; they are already decoded. You'll have to use a different method.
You can use the codecs.decode()
function to apply hex
as a codec:
>>> import codecs
>>> codecs.decode('ab', 'hex')
b'\xab'
This applies a Binary transform codec; it is the equivalent of using the base64.b16decode()
function, with the input string converted to uppercase:
>>> import base64
>>> base64.b16decode('AB')
b'\xab'
You can also use the binascii.unhexlify()
function to 'decode' a sequence of hex digits to bytes:
>>> import binascii
>>> binascii.unhexlify('ab')
b'\xab'
Either way, you'll get a bytes
object.
Upvotes: 15