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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18298251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:25:32  来源:igfitidea点击:

python, hex values to convert to a string/integer

pythonstringhex

提问by Sazzy

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 aand b:

ab 的预期结果:

>>> 9144776592
>>> '4445414442454546'

Thank you.

谢谢你。

采纳答案by alecxe

>>> 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 explanationwhy:

请注意,使用起来并不好encode('hex')- 以下是原因的解释

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.

您使用十六进制编解码器的方式在 Python 2 中起作用,因为您可以在 Python 2 中对 8 位字符串调用 encode(),即您可以对已经编码的内容进行编码。那没有意义。encode() 用于将 Unicode 字符串编码为 8 位字符串,而不是用于将 8 位字符串编码为 8 位字符串。

在 Python 3 中,您不能再对 8 位字符串调用 encode(),因此十六进制编解码器变得毫无意义并被删除了。

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

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

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

回答by falsetru

Using binascii.hexlify:

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

回答by Ashwini Chaudhary

Use binascii.hexlify:

使用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 strinstead of bytes:

如果你想要str而不是字节:

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