gpt4 book ai didi

python,十六进制值转换为字符串/整数

转载 作者:太空狗 更新时间:2023-10-30 01:54:51 24 4
gpt4 key购买 nike

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

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

ab 的预期结果:

>>> 9144776592
>>> '4445414442454546'

谢谢。

最佳答案

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

关于python,十六进制值转换为字符串/整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com