Convert an integer or float to hex in Python

Convert an integer or float to hex in Python :

In this tutorial, we will learn how to find out the hex value of an integer or floating value in python.

Using hex() method :

Method hex() is used to find out the hex value of an integer number. The syntax of this method is like below :

hex(x)

It takes only one parameter. The parameter should be an int number or it should define a __index()__ method that returns an integer value.
It will convert the provided integer value to hexadecimal and returns the result in string format.
Let me show you with one example of how it works :

print("Hex value for 2 is ",hex(2))
print("Hex value for 3 is ",hex(3))
print("Hex value for 16 is ",hex(16))
print("Hex value for 7 is ",hex(7))
print("Hex value for 21 is ",hex(21))

It will print out the below output :

Hex value for 2 is  0x2
Hex value for 3 is  0x3
Hex value for 16 is  0x10
Hex value for 7 is  0x7
Hex value for 21 is  0x15

python convert integer to hex

As you can see that 0x is prefixed with all strings indicating that the string is a hexadecimal representation.
Now, let’s try to find out the hex value of a float using the same method :

print("Hex value for 2.3 is ",hex(2.3))

It will throw one error like below :

Traceback (most recent call last):
  File "example.py", line 2, in 
    print("Hex value for 2.3 is ",hex(2.3))
TypeError: 'float' object cannot be interpreted as an integer

That means we cannot use this method for float numbers.

Finding hex values for float :

As we have seen above, we cannot use hex() method to find the hex values for floating numbers. To find the hexadecimal value for floating numbers in python, we can use float.hex() method. This method takes one float as an input argument and returns the hexadecimal string as like below. Example :

print("Hex value for 2.4 is ",float.hex(2.4))
print("Hex value for 21.14 is ",float.hex(21.14))
print("Hex value for 2.41 is ",float.hex(2.41))
print("Hex value for 10.4 is ",float.hex(10.4))

The output will be :

Hex value for 2.4 is  0x1.3333333333333p+1
Hex value for 21.14 is  0x1.523d70a3d70a4p+4
Hex value for 2.41 is  0x1.347ae147ae148p+1
Hex value for 10.4 is  0x1.4cccccccccccdp+3


Conclusion :

We have learned how to find the hexadecimal values of integer and floating point numbers in python. Try to run the examples explained above and drop one comment below if you have any queries.

You might also like :

Leave a Reply