Python’s hex() Function

Python’s hex() function is a built-in method that converts integers to hexadecimal strings. Understanding how to use hex() effectively can be invaluable, especially in scenarios where hexadecimal representation is required. In this article, we’ll dive into the intricacies of hex() with comprehensive examples to help you grasp its functionality better.

Basic Usage:

# Example 1: Converting an integer to hexadecimal
num = 255
hex_num = hex(num)
print(hex_num)


Output:

0xff


In this example, the integer 255 is converted to its hexadecimal representation '0xff' using the hex() function.

Negative Integers:

# Example 2: Converting a negative integer to hexadecimal
negative_num = -42
hex_negative_num = hex(negative_num)
print(hex_negative_num)


Output:

'-0x2a'


Even negative integers can be converted to their hexadecimal representation using hex(), prefixed with -0x.

Floating-Point Numbers:

# Example 3: Converting a floating-point number to hexadecimal
float_num = 3.14
try:
hex_float_num = hex(float_num)
except TypeError as e:
print(e)


Output:

'hex() argument can't be converted to hex'


hex() only works with integers. Attempting to use it with floating-point numbers raises a TypeError.

Using hex() with Custom Objects:

# Example 4: Converting a custom object to hexadecimal
class MyClass:
def __init__(self, value):
self.value = value

my_obj = MyClass(42)
try:
hex_obj = hex(my_obj)
except TypeError as e:
print(e)


Output:

'hex() argument can't be converted to hex'


hex() cannot directly convert custom objects to hexadecimal strings. It only works with integers.

# Example 5: Converting a hexadecimal string back to an integer
hex_str = '0x1a'
int_from_hex = int(hex_str, 16)
print(int_from_hex)


Output:

26


You can convert a hexadecimal string back to an integer using the int() function, specifying the base as 16.

Author: user