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.
1 2 3 4 5 6 |
print(hex(255)) # decimal print(hex(0b111)) # binary print(hex(0o77)) # octal print(hex(0XFF)) # hexadecimal |
Output:
1 2 3 4 5 6 |
0xff 0x7 0x3f 0xff |
Python hex() with object
Let’s create a custom class and define __index__() function so that we can use hex() function with it.
1 2 3 4 5 6 7 8 9 10 |
class Data: id = 0 def __index__(self): print('__index__ function called') return self.id d = Data() d.id = 100 print(hex(d)) |
Output:
1 2 3 4 |
__index__ function called 0x64 |
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: Official Documentation