English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Funções do Python

Tipos de Dados do Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python hex() usage and examples

Built-in functions in Python

The hex() function converts an integer to the corresponding hexadecimal string.

The syntax of hex() is:

hex(x)

hex() parameters

The hex() function takes a single parameter.

x-Integer (int object or must define __index__() returning an integer method)

hex() return value

The hex() function converts an integer to the corresponding hexadecimal string and then returns it.

The returned hexadecimal string starts with the prefix '0x', indicating that it is in hexadecimal form.

Example1: How does hex() work?

number = 435
print(number, 'Hexadecimal =', hex(number))
number =
print(number, 'Hexadecimal =', hex(number))
number = -34
print(number, 'Hexadecimal =', hex(number))
returnType = type(hex(number))
print('The return type of hex() is', returnType)

When running the program, the output is:

435 Hexadecimal = 0x1b3
0 Hexadecimal = 0x0
-34 Hexadecimal = -0x22
The return type of hex() is <class 'str'>

If you need to find the hexadecimal representation of a floating-point number, you need to use the float.hex() method.

Example2: Hexadecimal representation of floating-point numbers

number = 2.5
print(number, 'hex =', float.hex(number))
number = 0.0
print(number, 'hex =', float.hex(number))
number = 10.5
print(number, 'hex =', float.hex(number))

When running the program, the output is:

2.5 hex = 0x1.4000000000000p+1
0.0 hex = 0x0.0p+0
10.5 hex = 0x1.5000000000000p+3

Built-in functions in Python