Hexadecimal Numbers
Understanding Hexadecimal
Hexadecimal (base 16) is a number system that uses 16 digits: 0-9 and A-F (or a-f). It's commonly used in computer science for representing memory addresses, colors, and other data.
Representing Hexadecimal Numbers in Python
To represent a hexadecimal number in Python, you prefix it with 0x
or 0X
:
Python
hex_number =
0xFF
# Equivalent to decimal 255
Converting Between Decimal and Hexadecimal
· Decimal to Hexadecimal:
o
Use the hex()
function:
Python
decimal_number =
255
hex_string =
hex(decimal_number)
# Output: '0xff'
· Hexadecimal to Decimal:
o
Use the int()
function with base 16:
Python
hex_string =
'0xff'
decimal_number =
int(hex_string,
16)
# Output: 255
Bitwise Operations with Hexadecimal
You can perform bitwise operations on hexadecimal numbers just like with decimal or binary numbers.
Python
x =
0xA
# Decimal 10
y =
0x5
# Decimal 5
result_and = x & y
# Output: 0 (Binary: 0000)
result_or = x | y
# Output: 0xF (Binary: 1111)
Key Points
· Hexadecimal numbers provide a compact way to represent binary data.
· Python offers built-in functions for converting between decimal and hexadecimal.
· Bitwise operations can be performed on hexadecimal numbers.