Python hex(): Convert Numbers to Hexadecimal

The hex() function converts an integer into a hexadecimal string. It’s useful for working with memory addresses, color codes, cryptography, and low-level programming.

Example

num = 255
print(hex(num))  
# Output: '0xff'

The output '0xff' represents 255 in hexadecimal (base 16).

Syntax

hex(number)
  • number → An integer to convert.
  • Returns → A string starting with '0x', indicating hexadecimal.

1. Converting Multiple Numbers to Hex

print(hex(10))   # Output: '0xa'
print(hex(100))  # Output: '0x64'
print(hex(500))  # Output: '0x1f4'

Great for low-level number representation.

2. Removing the ‘0x’ Prefix

num = 255
print(format(num, "x"))  
# Output: 'ff'

Useful for color codes or compact hexadecimal values.

3. Using hex() in Memory Addressing

Python uses hex() to display memory locations.

x = 100
print(hex(id(x)))  
# Output: Memory address in hex (varies)

This is helpful in debugging memory-related operations.

4. Converting Negative Numbers

Hex supports negative numbers, keeping the - sign.

print(hex(-42))  
# Output: '-0x2a'

Useful for signed integer representations.

Key Notes

  • Converts integers to hexadecimal format.
  • Useful for memory, cryptography, and colors.
  • Works with both positive and negative numbers.
  • Prefix 0x can be removed for cleaner output.

By using hex(), you can work with hexadecimal numbers efficiently, making it essential for programming, networking, and digital systems. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top