Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert hex to decimal in Python? [duplicate]

People also ask

Can Python convert hex to decimal?

Python module provides an int() function which can be used to convert a hex value into decimal format. It accepts 2 arguments, i.e., hex equivalent and base, i.e. (16). int() function is used to convert the specified hexadecimal number prefixed with 0x to an integer of base 10.

How do you convert hex to decimal to decimal?

The conversion of hexadecimal to decimal is done by using the base number 16. The hexadecimal digit is expanded to multiply each digit with the power of 16. The power starts at 0 from the right moving forward towards the right with the increase in power. For the conversion to complete, the multiplied numbers are added.

How do you convert hexadecimal to double?

X = hex2num( hexStr ) converts hexStr to the double-precision floating-point number that it represents. The input argument hexStr has up to 16 characters representing a number in its IEEE® format using hexadecimal digits.

How do you convert hex to float in Python?

int i = 0x41973333; float f = *((float*)&i); and that's exactly what the Python code using the ctypes library is doing in my example. I used your method to convert a hex string to float and it returns a wrong value.


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.


>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.


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