Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 bytes to hex string

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?

like image 961
MightyPork Avatar asked Nov 19 '14 17:11

MightyPork


People also ask

How to read bytes as hex in Python?

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.

How do you convert bytes to hexadecimal?

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.

How do you create a hex string in Python?

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.


1 Answers

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.

like image 103
Martijn Pieters Avatar answered Sep 20 '22 01:09

Martijn Pieters