lettura simple

Hexadecimal Numbers in Python

Python offers a versatile way to represent integers: the hexadecimal system.

So, what exactly are hexadecimal numbers? They're part of a base-16 system that employs sixteen unique symbols. The first ten are identical to our familiar decimal numbers, and the remaining six range from the letters "A" to "F".

To specify a number in hexadecimal, simply use the 0x or 0X prefix.

Let's take an example. Suppose you want to assign the hexadecimal value FF to a variable named "x"

x = 0xff

Now, when you prompt Python to display the value of "x", it will automatically present its equivalent in decimal.

print(x)

Here, the hexadecimal FF translates to the decimal 255.

255

To shift a decimal number to its hexadecimal counterpart, the hex() function is your go-to

hex(255)

0xff

On the flip side, if you're looking to convert a hexadecimal value back to decimal, the int() function has you covered

int(0xff)

255

But there's more. Python also allows for string formatting to display numbers in hexadecimal.

Using the 'x' and 'X' placeholders, you can print numbers in either lowercase or uppercase hexadecimal format.

num = 255
print(f"{num:x}")
print(f"{num:X}")

The output will be 'ff' and 'FF', respectively.

ff
FF

In essence, Python provides a robust toolkit for anyone looking to delve into the world of hexadecimal numbers.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin