Convert hex string to int in Python

394    Asked by Aashishchaursiya in Python , Asked on Apr 1, 2021

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

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


You can convert hex to int 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)

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

 print int("0xfff", 0)

 print int("10", 0)

It is important to identify 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)



Your Answer

Interviews

Parent Categories