在Python中將十六進製字符串轉換為int

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

讓`int`推斷

``````>>> int(string_1, 0)
65535
``````

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

文字：

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

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

Python數字以數字字符開頭，而Python名稱不能以數字字符開頭。

'0x'前綴，你也可以使用eval函數

``````>>a='0xff'
>>eval(a)
255
``````

``````x = int("deadbeef", 16)
``````

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

（您必須指定`0`作為基礎才能調用此前綴猜測行為;省略第二個參數表示假設基數為10）。

``````>>a = int('deadbeef',16)
>>float(a)
3735928559.0
``````

``````int(s, 16)
``````

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

>>> hex_to_int("c0ffee")
12648430
``````

請不要這樣做！

``````~ (0xffffffff - int('0xdeadbeef', 16)) + 1
``````