6

I'm looking how I can take hex values, and turn them into a string or an integer. Examples:

>>> a = b'\x91\x44\x77\x65\x92'
>>> b = b'\x44\x45\x41\x44\x42\x45\x45\x46'
>>> a
>>> �Dwe�
>>> b
>>> 'DEADBEEF'

Desired results for a and b:

>>> 9144776592
>>> '4445414442454546'

Thank you.

3 Answers 3

8
>>> a = b'\x91\x44\x77\x65\x92'
>>> a.encode("hex")
'9144776592'
>>> b.encode('hex')
'4445414442454546'

Note, that it's not nice to use encode('hex') - here's an explanation why:

The way you use the hex codec worked in Python 2 because you can call encode() on 8-bit strings in Python 2, ie you can encode something that is already encoded. That doesn't make sense. encode() is for encoding Unicode strings into 8-bit strings, not for encoding 8-bit strings as 8-bit strings.

In Python 3 you can't call encode() on 8-bit strings anymore, so the hex codec became pointless and was removed.

Using binascii is easier and nicer, it is designed for conversions between binary and ascii, it'll work for both python 2 and 3:

>>> import binascii
>>> binascii.hexlify(b'\x91\x44\x77\x65\x92')
b'9144776592'
Sign up to request clarification or add additional context in comments.

Comments

3

Use binascii.hexlify:

In [1]: from binascii import hexlify

In [2]: a = b'\x91\x44\x77\x65\x92'

In [3]: hexlify(a)
Out[3]: b'9144776592'

In [4]: b = b'\x44\x45\x41\x44\x42\x45\x45\x46'

In [5]: hexlify(b)
Out[5]: b'4445414442454546'

If you want str instead of bytes:

In [7]: hexlify(a).decode('ascii')
Out[7]: '9144776592'

Comments

1

Using binascii.hexlify:

>>> import binascii
>>> a = b'\x91\x44\x77\x65\x92'
>>> b = b'\x44\x45\x41\x44\x42\x45\x45\x46'
>>> binascii.hexlify(a)
b'9144776592'
>>> binascii.hexlify(b)
b'4445414442454546'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.