Python Glossary Русский

all Python 3Arithmetic & operatorsterm

Bitwise operators

bitwise

Operators that work on numbers bit by bit: & (AND), | (OR), ^ (XOR), ~ (NOT/inversion), << (left shift), >> (right shift).

Syntax

a & b  a | b  a ^ b  ~a  a << n  a >> n

Precedence bites first: bitwise operators bind more loosely than arithmetic, so x & 1 + 1 parses as x & (1 + 1) and 1 << n - 1 as 1 << (n - 1) — add parentheses. With comparisons it is the other way round, unlike C: x & 1 == 0 means (x & 1) == 0. Python ints are arbitrary precision and behave as two's complement, so ~x is always -x - 1, a left shift never overflows (the number just grows), and >> keeps the sign of a negative value. A negative shift count raises ValueError.

Examples

print(0b1100 & 0b1010)  # → 8   (0b1000)
print(0b1100 | 0b1010)  # → 14  (0b1110)
print(0b1100 ^ 0b1010)  # → 6   (0b0110)
print(~5)               # → -6
print(1 << 3)           # → 8
print(16 >> 2)          # → 4

See also

Open in the full glossarydocs.python.orgReport an inaccuracy