The Python Oracle

How do I convert hex to decimal in Python?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 How Do I Convert Hex To Decimal In Python?
00:11 Answer 1 Score 59
00:21 Accepted Answer Score 351
00:40 Answer 3 Score 23
01:02 Thank you

--

Full question
https://stackoverflow.com/questions/9210...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #hex #decimal

#avk47



ACCEPTED ANSWER

Score 351


If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.




ANSWER 2

Score 59


>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.




ANSWER 3

Score 23


You could use a literal eval:

>>> ast.literal_eval('0xdeadbeef')
3735928559

Or just specify the base as argument to int:

>>> int('deadbeef', 16)
3735928559

A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:

>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100