在Python中将十六进制字符串转换为整数

发布于 2024-07-07 01:43:36 字数 90 浏览 5 评论 0原文

如何将十六进制字符串转换为整数?

"0xffff"   ⟶   65535
"ffff"     ⟶   65535

How do I convert a hex string to an integer?

"0xffff"   ⟶   65535
"ffff"     ⟶   65535

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

蓝色星空 2024-07-14 01:43:36

没有0x前缀,您需要显式指定基数,否则无法区分:

x = int("deadbeef", 16)

0x > 前缀,Python 可以自动区分十六进制和十进制:(

>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10

您必须指定 0 作为基数才能调用此前缀猜测行为;如果省略第二个参数, int() 将假定以 10 为基数。)

Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:

x = int("deadbeef", 16)

With the 0x prefix, Python can distinguish hex and decimal automatically:

>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, int() will assume base-10.)

腹黑女流氓 2024-07-14 01:43:36

int(hexstring, 16) 就可以解决这个问题,无论有没有 0x 前缀都可以:

>>> int("a", 16)
10
>>> int("0xa", 16)
10

int(hexstring, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa", 16)
10
淡淡離愁欲言轉身 2024-07-14 01:43:36

在Python中将十六进制字符串转换为int

我可能将其设置为“0xffff”或只是“ffff”

要将字符串转换为 int,请将字符串连同要转换的基数一起传递给 int

两个字符串都足以以这种方式进行转换:

>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535

int 推断

如果您传递 0 作为基数,int 将从字符串中的前缀推断基数。

>>> int(string_1, 0)
65535

如果没有十六进制前缀,0xint 就没有足够的信息来猜测:

>>> int(string_2, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'

文字:

如果您在源代码或解释器中输入,Python 会将适合您的转换:

>>> integer = 0xffff
>>> integer
65535

这不适用于 ffff,因为 Python 会认为您正在尝试编写合法的 Python 名称:

>>> integer = ffff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined

Python 数字以数字字符开头,而 Python 名称不能以数字开头特点。

Convert hex string to int in Python

I may have it as "0xffff" or just "ffff".

To convert a string to an int, pass the string to int along with the base you are converting from.

Both strings will suffice for conversion in this way:

>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535

Letting int infer

If you pass 0 as the base, int will infer the base from the prefix in the string.

>>> int(string_1, 0)
65535

Without the hexadecimal prefix, 0x, int does not have enough information with which to guess:

>>> int(string_2, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'

literals:

If you're typing into source code or an interpreter, Python will make the conversion for you:

>>> integer = 0xffff
>>> integer
65535

This won't work with ffff because Python will think you're trying to write a legitimate Python name instead:

>>> integer = ffff
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ffff' is not defined

Python numbers start with a numeric character, while Python names cannot start with a numeric character.

少跟Wǒ拽 2024-07-14 01:43:36

对于任意给定的字符串 s:

int(s, 16)

For any given string s:

int(s, 16)
梅窗月明清似水 2024-07-14 01:43:36

添加上面 Dan 的答案:如果您为 int() 函数提供十六进制字符串,则必须将基数指定为 16,否则它不会认为您为其提供了有效值。 对于字符串中不包含的十六进制数字,不需要指定基数 16。

print int(0xdeadbeef) # valid

myHex = "0xdeadbeef"
print int(myHex) # invalid, raises ValueError
print int(myHex , 16) # valid

Adding to Dan's answer above: if you supply the int() function with a hex string, you will have to specify the base as 16 or it will not think you gave it a valid value. Specifying base 16 is unnecessary for hex numbers not contained in strings.

print int(0xdeadbeef) # valid

myHex = "0xdeadbeef"
print int(myHex) # invalid, raises ValueError
print int(myHex , 16) # valid
甜心小果奶 2024-07-14 01:43:36

请不要这样做!

>>> def hex_to_int(x):
    return eval("0x" + x)

>>> hex_to_int("c0ffee")
12648430

为什么使用“eval”是一种不好的做法吗?

15000 多个这样的例子。

Please don't do this!

>>> def hex_to_int(x):
    return eval("0x" + x)

>>> hex_to_int("c0ffee")
12648430

Why is using 'eval' a bad practice?

15000+ examples of this in the wild.

知你几分 2024-07-14 01:43:36

或者 ast.literal_eval (这是安全的,与 eval 不同):

ast.literal_eval("0xffff")

演示:

>>> import ast
>>> ast.literal_eval("0xffff")
65535
>>> 

Or ast.literal_eval (this is safe, unlike eval):

ast.literal_eval("0xffff")

Demo:

>>> import ast
>>> ast.literal_eval("0xffff")
65535
>>> 
两相知 2024-07-14 01:43:36

如果您使用Python解释器,您只需输入0x(您的十六进制值),解释器就会自动为您转换它。

>>> 0xffff

65535

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

>>> 0xffff

65535
乖乖 2024-07-14 01:43:36

格式化程序选项 '%x' % 似乎也适用于赋值语句。 (假设Python 3.0及更高版本)

示例

a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100

The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)

Example

a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
天气好吗我好吗 2024-07-14 01:43:36

处理十六进制、八进制、二进制、整数和浮点数

使用标准前缀(即 0x、0b、0 和 0o),此函数会将任何合适的字符串转换为数字。 我在这里回答了这个问题: https://stackoverflow.com/a/58997070/2464381 但这里是所需的功能。

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

Handles hex, octal, binary, int, and float

Using the standard prefixes (i.e. 0x, 0b, 0, and 0o) this function will convert any suitable string to a number. I answered this here: https://stackoverflow.com/a/58997070/2464381 but here is the needed function.

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文