The hex() is a built-in Python function that converts an integer number into a lowercase hexadecimal string prefixed with ‘0x’ (or ‘-0x’ for negative values).
Hexadecimal (base-16) uses digits 0-9 and a-f to represent values. The hex() does not modify the input and always returns a new string.
num = 255 hex_str = hex(num) print(hex_str) # Output: 0xff negative_num = -255 hex_neg_str = hex(negative_num) print(hex_neg_str) # Output: -0xff
As you can see from the above program, if the input is a positive number, it returns a string with the prefix “0x”. If the input is a negative number, it returns a string with the prefix “-0x”.
Syntax
hex(number)
Parameters
Argument | Description |
number (required) | It represents an integer to convert.
It can have a positive, negative, or zero value. If you pass Non-integer inputs, such as floats, strings, or other types, it will raise a TypeError. |
Large positive integer (Arbitrary Precision)
It does not matter if the input integer is bigger; it will still convert to a hex string.
We can utilize large integers beyond the 64-bit range typically used in cryptographic applications.
large_num = 12345678901234567888 hex_large = hex(large_num) print(hex_large) # Output: 0xab54a98ceb1f0ad0
Zero and Edge Cases
Let’s pass 0, 1, and 16 to the hex() method and observe the output.
print(hex(0)) # Output: 0x0 print(hex(1)) # Output: 0x1 print(hex(16)) # Output: 0x10
Usage with a memory address
You can pass an integer address to the hex() method, and it will return the hexadecimal string representation of that address.
address = 4096 print(hex(address)) # Output: 0x1000
TypeError: ‘float’ object cannot be interpreted as an integer
If the input is a floating-point number, it throws this error: TypeError: ‘float’ object cannot be interpreted as an integer.
floating_point = 3.14 try: result = hex(floating_point) print(result) except TypeError as e: print(e) # Output: 'float' object cannot be interpreted as an integer
It enforces strict integer input, and we used a try-except mechanism to handle potential errors and print them.
Another approach is to convert the float into an integer using the int() function and then pass it to the hex() function.
floating_point = 3.14 try: integer = int(floating_point) output = hex(integer) print(output) except TypeError as e: print(e) # Output: 0x3
Invalid argument count
If you pass either zero arguments or 2 arguments to the hex() method, it will throw TypeError.
try: result = hex() except TypeError as e: print(e) # Output: 'hex() takes exactly one argument (0 given)' try: result = hex(10, 20) except TypeError as e: print(e) # Output: 'hex() takes exactly one argument (2 given)'
Pass only a single argument, which should be a valid integer.