I have a bytes object:
a = b'067b'
How do I get a string from it? Like this:
"067b"
I've tried:
In [3]: str(a)
Out[3]: "b'067b'"
In [4]: import codecs
In [5]: codecs.decode(a,'hex')
Out[5]: b'\x06{'
In [6]: import binascii
In [7]: binascii.b2a_hex(a)
Out[7]: b'30363762'
In [8]: binascii.hexlify(a)
Out[8]: b'30363762'
Is there no way to do this?
The simplest way is to use the built-in function hex() to a byte literal. Alternatively, the hexlify() function from the binascii module can also be used to produce the same output.
To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st . This is a relatively slower process for large byte array conversion.
hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.
You simply want to decode from ASCII here, your bytestring is already representing hexadecimal numbers, in ASCII characters:
>>> a = b'067b'
>>> a.decode('ascii')
'067b'
Everything you tried is interpreting the bytes as numeric data instead, either as hexadecimal numbers representing bytes or as bytes representing numeric data.
So your first attempt takes the value 06
as a hexadecimal number and turns that into the byte value 6
, and 7b
is turned into the byte value 123, which is the ASCII codepoint for the {
character.
In your second attempt you are converting each byte to a hexadecimal representation of its numeric value. The 0
byte being interpreted as the integer number 48 (the ASCII codepoint for the '0'
character), which is 30
in hexadecimal. '6'
is 54, or 36
in hex, etc.
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