Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Python hex() Function

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc. Python will take care of converting them to hexadecimal format.

Python hex() Example

Let’s look into some simple examples of converting integer to hexadecimal number.

print(hex(255))  # decimal
print(hex(0b111))  # binary
print(hex(0o77))  # octal
print(hex(0XFF))  # hexadecimal

Output:

Python hex() with Object

Let’s create a custom class and define __index__() function so that we can use hex() function with it.

class Data:
    id = 0

    def __index__(self):
        print('__index__ function called')
        return self.id

d = Data()
d.id = 100

print(hex(d))

Output:

__index__ function called
0x64

Start Your Cloud Journey Today with Our Free Trial!

Dive into the world of cloud computing with our exclusive free trial offer. Experience the power, flexibility, and scalability of our cloud solutions firsthand.

Try for free!