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
Conclusion # The Python "AttributeError: 'str' object has no attribute 'decode'" occurs when we call the decode() method on a string that has already been decoded from bytes. To solve the error, remove the call to the decode() method as the string is already decoded.
decode() is a method specified in Strings in Python 2. This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.
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.
Use binascii
:
import binascii
binary_string = binascii.unhexlify(hex_string)
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