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 :
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 :
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 :
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 :
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 :
- Python program to convert a list to string
- Working with random in python , generate a number,float in range etc
- Python program to convert a string to an integer
- Python program to find a substring in a string
- Python program to pad zeros to a string
- Logical operators in Python : Explanation with example