Python Glossary Русский

all Python 3Algorithms & data structuresterm

Number bases

math

Conversion between the binary, octal, decimal and hexadecimal systems.

Syntax

bin(n), oct(n), hex(n)
int(s, base)

bin(), oct() and hex() hand back a string with a 0b/0o/0x prefix, not a number: you cannot add them arithmetically, and len(bin(n)) is two more than the digit count — use format(n, 'b') for bare digits. Parsing back is int(s, base), which tolerates the prefix, while int(s, 0) infers the base from that prefix. For negatives bin(-5) is '-0b101', a minus sign in front of the magnitude rather than a two's-complement pattern as in C.

Examples

# Десятичное → другие
print(bin(42))   # → 0b101010
print(oct(42))   # → 0o52
print(hex(42))   # → 0x2a
print(f'{42:b}')  # → 101010 (без префикса)
print(f'{42:o}')  # → 52
print(f'{42:x}')  # → 2a
print(f'{42:X}')  # → 2A
# Другие → десятичное
print(int('101010', 2))  # → 42
print(int('52', 8))      # → 42
print(int('2a', 16))     # → 42
print(int('0b101010', 2))  # → 42
# Литералы
a = 0b1010  # двоичный
b = 0o17    # восьмеричный
c = 0xff    # шестнадцатеричный
print(a, b, c)  # → 10 15 255
# Произвольное основание
def to_base(n, base):
    digits = '0123456789ABCDEF'
    if n < base: return digits[n]
    return to_base(n//base, base) + digits[n%base]
print(to_base(255, 16))  # → FF
print(to_base(10, 2))    # → 1010
# Форматирование с заполнением
print(f'{255:08b}')  # → 11111111
print(f'{15:04x}')   # → 000f
print(format(42, '08b'))  # → 00101010
# Перевод RGB hex
color = '#ff5733'
r, g, b = int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)
print(r, g, b)  # → 255 87 51
# ASCII и ord
print(ord('A'))  # → 65 (это 0x41)
print(hex(ord('A')))  # → 0x41

See also

Open in the full glossarydocs.python.orgReport an inaccuracy