python,十六进制值转换为string/integ

2024-05-14 23:48:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究如何获取十六进制值,并将其转换为字符串或整数。 示例:

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

ab的预期结果:

>>> 9144776592
>>> '4445414442454546'

谢谢你。


Tags: 字符串示例整数x65x46x41x91x45
3条回答
>>> a = b'\x91\x44\x77\x65\x92'
>>> a.encode("hex")
'9144776592'
>>> b.encode('hex')
'4445414442454546'

注意,使用encode('hex')并不好-这里有一个explanation为什么:

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.

使用binascii更简单、更好,它是为二进制和ascii之间的转换而设计的,适用于python 2和3:

>>> import binascii
>>> binascii.hexlify(b'\x91\x44\x77\x65\x92')
b'9144776592'

使用^{}

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'

如果要用str代替字节:

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

使用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'

相关问题 更多 >

    热门问题