Back

Explore Courses Blog Tutorials Interview Questions
0 votes
7 views
in Python by (47.6k points)

How do I convert a hex string to an int in Python?

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

1 Answer

0 votes
by (106k points)

You can convert hex string into an int in Python by following ways:-

  • You must put ‘0x’ prefix with hex string, it will specify the base explicitly, otherwise, there's no way to tell:

x = int("fff", 16)

image

  • We put the 0x prefix, which helps Python to distinguish between hex and decimal automatically.

 print int("0xfff", 0)

 print int("10", 0)

image

  • It is necessary to specify 0 as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter then it will assume base as -10. 

  • If you do not want to put 0x prefix then you can do by following way:-

        int(hexString, 16) is used and it works with and without the 0x prefix.

int("fff", 16) 

int("0xfff",16) 

 image

If you wish to learn more about Python, visit the Python tutorial and Python course by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 4, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...