The Python Oracle

How do I convert hex to decimal in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
00:21 Accepted answer (Score 326)
00:44 Answer 2 (Score 54)
00:58 Answer 3 (Score 20)
01:33 Thank you

--

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

Question links:
[Python]: http://en.wikipedia.org/wiki/Python_%28p...

Answer 1 links:
[Read the docs]: http://docs.python.org/library/functions...

--

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