Python conver integer to hexadecimal using hex()

Python hex() method explanation with example:

hex() is one of the important method in Python. This method is used to convert any integer value to hexadecimal string value. If it is not an integer, or if it is an another object, it should have one index() method defined, that returns one integer value.

In this post, we will learn how to use hex method with examples.

Definition of hex method:

hex method is defined as like below:


Here, i is an integer value and it returns one string, i.e. its hexadecimal value that is prefixed with 0x.

Example of hex method:

Let’s take a look at how to use hex() with examples.


It will print the below output:


How to find the hex method for a floating point value:

We can also find the hex value for a floating point value. For that, we need to use float.hex() method. For example,


This will throw one TypeError:

TypeError: 'float' object cannot be interpreted as an integer

So, we can use float.hex to parse a floating point value:


It will print:


How to convert a hexadecimal value to integer:

We can also convert a hexadecimal value to integer. For that, we need to use the int() method. This method takes one hexadecimal value and convert that to an integer.

Hex with a custom object:

As explained above, we need to define the index method that should return one integer value.

class SampleObject:
    def __index__(self):
        return 10

obj = SampleObject()


Here, SampleObject is a class that has index() method that returns one integer value. If you run this code, it will print the below output:


Which is the hexadecimal value of 10.

You might also like: