[Python] Convert between decimal numbers and hexadecimal numbers

Convert decimal to hexadecimal

In Python, we can use the built-in hex() function to convert a decimal number to a hexadecimal number

decimal = 12
hexadecimal = hex(decimal)
print(hexadecimal)  # '0xc'

Tips:  The returned result is a string

Convert hexadecimal to decimal

In Python, we can convert hexadecimal to decimal using the built-in function int()

grammatical format

int(string, 16)

Where string is a hexadecimal number, 16 is the base

# 12
int('0xc', 16)

We can also use Python's built-in function eval() to convert hexadecimal to decimal

hexadecimal = '0xc'
decimal = eval(hexadecimal)
print(decimal)  # 12

Guess you like

Origin blog.csdn.net/Hudas/article/details/130616461