HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

Convert hex string to integer in Python

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
convertpythonstringintegerhex

Problem

How do I convert a hex string to an integer?

"0xffff"   ⟶   65535
"ffff"     ⟶   65535

Solution

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.)

Code Snippets

x = int("deadbeef", 16)
>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10

Context

Stack Overflow Q#209513, score: 1507

Revisions (0)

No revisions yet.