Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex string to int in Python

Tags:

python

string

hex

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

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

like image 852
Matt Avatar asked Oct 16 '08 17:10

Matt


People also ask

How do you convert hex to int in Python?

You can convert the hexstring to an integer in Python using the literal_eval() method of the ast (Abstract Syntax Trees) library. We have to pass the hex string to the literal_eval() function, there are no parameters, the function converts the hex string into an integer.

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

How do you convert string to int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you read a hex string in Python?

hex() function in Python hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.


2 Answers

Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:

x = int("deadbeef", 16) 

With the 0x prefix, Python can distinguish hex and decimal automatically.

>>> print(int("0xdeadbeef", 0)) 3735928559 >>> print(int("10", 0)) 10 

(You must specify 0 as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter int() will assume base-10.)

like image 103
Dan Lenski Avatar answered Oct 18 '22 05:10

Dan Lenski


int(hexstring, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16) 10 >>> int("0xa", 16) 10 
like image 34
unwind Avatar answered Oct 18 '22 04:10

unwind