0 votes
1 view
in Python by (47.8k 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 (107k 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

Related questions

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
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...