Friday, April 10, 2009

Python: Base conversion from hex to dec


Share at Facebook

Lets learn about how to convert from Hexadecimal number into Decimal number, or a Decimal number into Hexadecimal number using Python scripting.

First of all conversion from a decimal number into Hexadecimal number. Below is the code just using "%X" from print function like C/C++

dec = 18446744073709551615
print "%X" % dec


This tiny code will output the Hexadecimal representation of 18446744073709551615 into FFFFFFFFFFFFFFFF, If you want the output into lowercase letters, just change %X into %x, it will turn the output letters into small caps.

Now see an example about converting a Hexadecimal string Integer number. Just using the int() function of Python, and defining the base of current string is 16.
hex = 'FFFFFFFFFFFFFFFF'
print int(hex, 16)

This will output 18446744073709551615 into screen as the integer representation of hex number FFFFFFFFFFFFFFFF

You can use hex() function of python to convert integer number into hexadecimal number, but it will return 0x at the front of the number, and L at the end of the number if it is very big. For example below code will output 0xffffffffffffffffL into screen.
dec = 18446744073709551615
print hex(dec)


If you want to remove the ox from the front, and L from the end, just use below code.
dec = 18446744073709551615
print hex(dec)[2:-1]

There might be other way to do this convention. But I don't know the other ways. If anyone feel interest, can add here.




2 comments:

Anonymous said...

It's not

print hex(dec)[2:-1]

it's

print hex(dec)[2:].rstrip('L')

because shorter numbers won't have the L at the end so you'd strip the least significant digit.

Anonymous said...

Also, don't name your hex string hex, you've just overridden the builtin function hex() in the current scope.