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 :

python int float to hex

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 :

python int float to hex

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 :

python int float to hex


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