Notes

`hex()` Function in Python [ English ]

< Prev Next >

1. Introduction

The hex() function in Python is a built-in function used to convert an integer number into its hexadecimal representation. The hexadecimal number is returned as a string prefixed with 0x, which indicates that the number is in base-16 (hexadecimal system).

The hexadecimal number system uses 16 symbols:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

It is widely used in computer programming, memory addresses, and color codes in web development.

2. Syntax

hex(number)

Parameter


3. Return Value

4. Basic Example

print(hex(10))

Output

0xa

Explanation

5. Example with a Larger Number

print(hex(255))

Output

0xff

Explanation

6. Removing the 0x Prefix

Sometimes we need only the hexadecimal digits.

num = 255
hex_value = hex(num)

print(hex_value[2:])

Output

ff

Explanation

7. Example with Negative Numbers

print(hex(-20))

Output

-0x14

Explanation

8. Practical Example

number = 100

hex_value = hex(number)

print("Decimal:", number)
print("Hexadecimal:", hex_value)

Output

Decimal: 100
Hexadecimal: 0x64

Explanation

9. Summary

< Prev Next >