Системы счисления

Простые типы / Числа / Integer

# decimal number system
n_decimal = 42

# octal number system
# (042 is a SyntaxError)
octal = 0o42
# octal is 34

# hexadecimal number system
hexadecimal = 0x42
# hexadecimal is 66

# binary number system
binary = 0b1010
# binary is 10

# 42 to decimal string
s_decimal = str(42)
# s_decimal is '42'

# 42 to octal string
s_octal = oct(42)
# s_octal is '0o52'

# 42 to hexadecimal string
s_hexadecimal = hex(42)
# s_hexadecimal is '0x2a'

# 42 to binary string
s_binary = bin(42)
# s_binary is '0b101010'

# Without the prefix: x, o or b
s_plain = format(42, "x")
# s_plain is '2a'

# String in any base back to int
from_hexadecimal = int("2a", 16)
# from_hexadecimal is 42

# Base 0: the prefix decides
from_binary = int("0b101010", 0)
# from_binary is 42

print(f"{octal = }")
print(f"{hexadecimal = }")
print(f"{binary = }")
print(f"{s_decimal = }")
print(f"{s_octal = }")
print(f"{s_hexadecimal = }")
print(f"{s_binary = }")
print(f"{s_plain = }")
print(f"{from_hexadecimal = }")
print(f"{from_binary = }")