Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 149 ยท Operators

Bitwise Operators and Precedence

Learn Python's bitwise operators &, |, ^, ~, << and >> with binary examples, flags and bitmasks, plus the full operator precedence table and its common traps.

Every integer in your computer is stored as a row of bits: ones and zeros. Most of the time you never think about them, but sometimes you want to work on those bits directly: packing several yes/no options into one number, reading the red, green and blue parts of a color, or checking file permissions. Bitwise operators do exactly that. They compare or move the individual bits of integers.

In this lesson you'll learn the six bitwise operators, see how Python handles negative numbers, use bitmasks for flags, and finish with the complete operator precedence table, which tells you how Python groups any expression you write.

Seeing the bits

Before you can work with bits, you need to see them. bin() shows an integer in binary, and an f-string with the b format adds padding so numbers line up. You can also write binary literals directly with the 0b prefix:

Python Integers in binary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each position is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. So 0b00001100 is 8 + 4 = 12. bit_length() tells you how many bits a number needs, and bit_count() (Python 3.10+) counts the ones.

The six bitwise operators

Operator Name Result bit is 1 when...
a & b AND both bits are 1
a | b OR at least one bit is 1
a ^ b XOR (exclusive or) exactly one bit is 1
~a NOT (invert) the bit was 0 (see negatives below)
a << n left shift bits move n places left
a >> n right shift bits move n places right

The first three work position by position, comparing bit 0 of a with bit 0 of b, bit 1 with bit 1, and so on:

Python AND, OR and XOR side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the columns from top to bottom: AND keeps only the bits both numbers share, OR combines them, and XOR keeps the bits where they differ.

Shifts

Shifting left by n adds n zeros on the right, which multiplies by 2 to the power of n. Shifting right drops the lowest n bits, which is floor division by 2 to the power of n:

Python Shifting bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python integers have no fixed size, so << never overflows: 1 << 100 is a perfectly good 31-digit number. That's different from languages like C or JavaScript, where integers wrap around after 32 or 64 bits. A negative shift count, such as 1 << -1, raises a ValueError.

Negative numbers and ~

~x flips every bit. But a Python integer behaves as if it had an infinite row of sign bits on the left: zeros for positive numbers and ones for negative numbers. Flipping all of them turns a positive number into a negative one, and the rule works out to a simple formula: ~x == -x - 1.

Python Inverting bits with ~

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If you came from a language with fixed-size integers, this is the main surprise. When you need "the bits of an 8-bit or 32-bit value", combine ~ with a mask such as 0xFF (eight ones) or 0xFFFFFFFF (32 ones). The & keeps only the bits inside the mask.

Flags and bitmasks

The classic use for bitwise operators is storing several on/off options in one integer. Give each option its own bit, then:

  • combine options with |,
  • test for one with &,
  • remove one with & ~,
  • toggle one with ^.
Python Permissions as bit flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is exactly how Unix file permissions work: 0o754 is three groups of three bits for the owner, the group and everyone else. The augmented forms |=, &=, ^=, <<= and >>= update a variable in place, just like the assignment operators you already know.

Reading packed values: colors

Masks and shifts also pull apart numbers that pack several values together. A web color like #FF8C1A is one 24-bit number holding three 8-bit channels:

Python Unpacking an RGB color

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A nicer way: enum.Flag

Raw integer flags are compact but easy to misuse: nothing stops you from mixing up a permission with a color. Python's enum.Flag gives each bit a name and supports the same operators. You'll learn it properly in the Enums lesson; here's a preview:

Python
from enum import Flag, auto

class Perm(Flag):
    READ = auto()      # 1
    WRITE = auto()     # 2
    EXECUTE = auto()   # 4

mode = Perm.READ | Perm.WRITE
print(mode)                  # Perm.READ|WRITE
print(Perm.WRITE in mode)    # True

Small tricks (and when to skip them)

A few bitwise idioms appear often in other people's code:

  • n & 1 is 1 for odd numbers and 0 for even ones.
  • n & (n - 1) == 0 is true when a positive n is a power of two.
  • a ^= b; b ^= a; a ^= b swaps two integers without a temporary.

They work, but in Python they're rarely faster than the obvious version, and they're harder to read. Prefer n % 2 == 1 and a, b = b, a. Save bit tricks for code that really deals with bits: binary file formats, network protocols, hardware registers, hashes and compact flag sets.

Bitwise operators on other types

Several built-in types reuse these symbols with a related meaning:

Python &, | and ^ beyond integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You met set operations in Sets and dictionary merging in Dictionary Methods.

& is not and. On booleans, & gives the same answer as and, but it always evaluates both sides (no short-circuit) and it binds more tightly than comparisons. Use and/or for conditions. The one common exception is NumPy and pandas, where & and | combine arrays of conditions, and every condition needs its own parentheses.

The full precedence table

Arithmetic Operators introduced precedence for math. Here is the whole table, from the operators that bind most tightly (evaluated first) to the loosest:

Level Operators Meaning
1 (...), [...], {...} parentheses and displays
2 x[i], x[a:b], f(...), x.attr subscription, slicing, calls, attributes
3 await x await
4 ** exponent (right to left)
5 +x, -x, ~x unary plus, minus, bitwise NOT
6 *, @, /, //, % multiplication and division
7 +, - addition and subtraction
8 <<, >> shifts
9 & bitwise AND
10 ^ bitwise XOR
11 | bitwise OR
12 in, not in, is, is not, <, <=, >, >=, !=, == comparisons (chainable)
13 not x boolean NOT
14 and boolean AND
15 or boolean OR
16 x if c else y conditional expression
17 lambda lambda
18 := assignment expression (walrus)

Operators on the same level group left to right, except **, which groups right to left. All comparisons share one level and chain: a < b < c means a < b and b < c.

Two places in this table regularly surprise people. Run this and compare each pair:

Python Precedence traps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second example prints False even though both numbers are positive: 0 & b is evaluated first, then the comparison chain 5 > 0 > 0 fails. When an expression mixes bitwise operators with anything else, add parentheses. They cost nothing and make your intent clear to the next reader.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 12 & 10? (12 is 0b1100, 10 is 0b1010)

    AND keeps only the bits set in both numbers. 1100 & 1010 = 1000, which is 8.
  2. 2. What does ~5 evaluate to in Python?

    Python integers behave like infinite two's complement, so ~x always equals -x - 1.
  3. 3. perms holds several flags. Which line removes the WRITE flag and leaves the others unchanged?

    ~WRITE has every bit set except WRITE's, so AND-ing clears just that bit. ^= would add the flag back if it was missing, and subtraction breaks when the flag isn't set.
  4. 4. What does 1 << 2 + 1 evaluate to?

    + binds more tightly than <<, so Python computes 1 << 3, which is 8.
  5. 5. Why does a > 0 & b > 0 give a surprising result?

    Bitwise operators sit above comparisons in the precedence table. Use and (or parentheses around each comparison).

Summary

  • bin(), f"{n:08b}" and 0b... literals let you see and write bits; bit_length() and bit_count() measure them.
  • & (AND), | (OR) and ^ (XOR) combine bits position by position; << and >> multiply or floor-divide by powers of two.
  • Python integers never overflow, and ~x equals -x - 1; use a mask like 0xFF to work with a fixed number of bits.
  • For flags: combine with |, test with &, remove with & ~, toggle with ^. enum.Flag gives the same power with names.
  • |, & and ^ also mean union, intersection and symmetric difference for sets, and | merges dictionaries.
  • Precedence runs from calls and attributes, through **, unary, arithmetic, shifts, &, ^, |, then comparisons, not, and, or. When in doubt, add parentheses.

Next: if, elif and else, where your conditions finally start making decisions.