Python Numbers and Math · Lesson 18 of 149

Python Bitwise Operators and Number Bases

What you will learn

  • Writing numbers in binary, octal and hexadecimal
  • Converting with bin, oct, hex, format and int(text, base)
  • The bitwise operators: &, |, ^, ~, <<, >>
  • Practical uses: even or odd, flags, packing colours
  • Where bitwise operators sit in the order of operations

1. Number bases

We normally write numbers in base 10, with ten digits 0 to 9. Computers work in base 2 (binary), with only 0 and 1. Programmers also use base 8 (octal) and base 16 (hexadecimal, with digits 0 to 9 and a to f).

Base Name Digits Python prefix Example for 255
2 binary 0 1 0b 0b11111111
8 octal 0 to 7 0o 0o377
10 decimal 0 to 9 none 255
16 hexadecimal 0 to 9, a to f 0x 0xff

Writing a number with a prefix is just another way to write the same int:

print(0b101, 0o17, 0xff)
print(0xff == 255, 0b1111_0000)
5 15 255
True 240

(Underscores work here too, as in 0b1111_0000, lesson 3.1.) Inside, it is the same number whichever way you write it.

Quick check: what is `0b101` in ordinary decimal?

5: one four, no twos and one one (4 + 0 + 1).

2. Converting a number to another base

Three built-in functions give the text of a number in another base:

print(bin(10), oct(10), hex(255))
print(bin(-5), hex(-255))
0b1010 0o12 0xff
-0b101 -0xff

For more control, use format or an f-string with these codes:

Code Meaning
b binary
o octal
x / X hexadecimal, lower or upper case
# before add the 0b, 0o or 0x prefix
08b binary, padded with zeros to 8 digits
print(format(10, "b"), format(10, "08b"))
print(format(255, "x"), format(255, "X"), format(255, "#x"))
1010 00001010
ff FF 0xff

3. Converting text to a number

int(text, base) reads text written in a base (lesson 2.4). With base 0, Python reads the prefix itself:

print(int("1010", 2), int("ff", 16), int("17", 8))
print(int("0b1010", 0), int("0xff", 16))
10 255 15
10 255

A digit that does not exist in the base is an error: int("12", 2) raises ValueError: invalid literal for int() with base 2: '12'.

4. The bitwise operators

A bitwise operator works on the individual bits (the 0s and 1s) of whole numbers. Take x = 0b1100 (12) and y = 0b1010 (10):

Operator Name Rule for each bit x op y
x & y AND 1 only if both are 1 0b1000 (8)
x | y OR 1 if either is 1 0b1110 (14)
x ^ y XOR 1 if they are different 0b0110 (6)
~x NOT flips every bit -13
x << n shift left moves bits left by n x * 2 ** n
x >> n shift right moves bits right by n x // 2 ** n
x = 0b1100
y = 0b1010
print(f"{x:04b} & {y:04b} = {x & y:04b}")
print(f"{x:04b} | {y:04b} = {x | y:04b}")
print(f"{x:04b} ^ {y:04b} = {x ^ y:04b}")
1100 & 1010 = 1000
1100 | 1010 = 1110
1100 ^ 1010 = 0110

Bit by bit for &: the left bit is 1 & 1 = 1, then 1 & 0 = 0, 0 & 1 = 0 and 0 & 0 = 0, which gives 1000.

Shifts

Shifting left by one doubles the number, and shifting right by one halves it, rounding down:

print(5 << 1, 5 << 3, 20 >> 2, 1 << 10)
print(-20 >> 2, -5 >> 1)
10 40 5 1024
-5 -3

So 1 << 10 is a quick way to write 2 to the power of 10. A negative shift count is an error: 5 << -1 raises ValueError: negative shift count.

NOT is minus one more

~x flips all the bits, which in Python gives -(x + 1):

print(~5, ~0, ~-1, ~255)
-6 -1 0 -256

Bitwise operators work on int only. Using them on a float is a TypeError: 5.0 & 3 fails with unsupported operand type(s) for &: 'float' and 'int'.

5. Practical bit tricks

Odd or even

The last bit of a whole number is 1 for odd and 0 for even:

print(37 & 1, 38 & 1)
1 0

Flags: several yes/no options in one number

Give each option its own bit, and combine them:

READ, WRITE, EXEC = 1, 2, 4

flags = 0
flags |= READ | EXEC
print(flags, bool(flags & READ), bool(flags & WRITE), bool(flags & EXEC))
flags &= ~READ
print(flags)
flags ^= WRITE
print(flags)
5 True False True
4
6
  • |= turns on a flag.
  • & flag tests whether a flag is on.
  • &= ~flag turns off a flag.
  • ^= flag toggles a flag.

File permissions on many systems use exactly this idea.

Is it a power of two?

A power of two has a single 1 bit, so n & (n - 1) is 0:

for n in [1, 2, 3, 8, 12, 64]:
    print(n, n > 0 and n & (n - 1) == 0)
1 True
2 True
3 False
8 True
12 False
64 True

Counting bits

print((5).bit_length(), (255).bit_length(), (256).bit_length())
print((5).bit_count(), bin(37).count("1"))
3 8 9
2 3

bit_length() is the number of bits needed. bit_count() counts the 1 bits (it needs Python 3.10 or later); bin(n).count("1") works in any version.

6. Where bitwise operators fit in the order

Bitwise operators come after arithmetic and before comparisons. From highest to lowest: **, unary + - ~, * / // %, + -, << >>, then &, then ^, then |, then comparisons.

print(1 + 2 << 3, 1 + (2 << 3))
print(6 & 3 | 8)
24 17
10

1 + 2 << 3 is (1 + 2) << 3, because + goes first. As always, use brackets to make your meaning clear: (3 & 5) == 1.

Worked example: pack a colour into one number

A web colour has three parts: red, green and blue, each from 0 to 255. Pack (255, 128, 0) into one number, then take the parts out again.

r, g, b = 255, 128, 0
colour = (r << 16) | (g << 8) | b
print(hex(colour))

print(colour >> 16)
print((colour >> 8) & 255)
print(colour & 255)
0xff8000
255
128
0
Step What it does
r << 16 moves red into the top byte
g << 8 moves green into the middle byte
| joins the three parts
colour >> 16 brings red back down
(colour >> 8) & 255 brings green down, then keeps only its 8 bits
colour & 255 keeps only the last 8 bits (blue)

0xff8000 is the web colour #ff8000. The numbers are made up for the example.

Common mistakes

  • Using ^ for a power. ^ is XOR; the power is **.
  • Confusing and and &. and combines true/false answers; & works on the bits of numbers.
  • Forgetting brackets. x & 1 == 0 works, but (x & 1) == 0 is clearer.
  • Reading ~5 as -5. It is -6, because ~x is -(x + 1).
  • Using bitwise operators on floats, which gives a TypeError.

Key takeaways

  • Write other bases with prefixes 0b, 0o, 0x; convert with bin, oct, hex, format and int(text, base).
  • &, | and ^ combine bits (AND, OR, XOR); ~x is -(x + 1).
  • x << n multiplies by 2 ** n; x >> n divides by 2 ** n, rounding down.
  • Bits are used for flags, odd/even tests and packing values.
  • Bitwise operators sit after + - and before comparisons; use brackets.

Practice

1. What are bin(12) and hex(255)?

Show answer

0b1100 and 0xff.

2. What does int("101", 2) give? And int("1f", 16)?

Show answer

5 and 31.

3. What do 6 & 3, 6 | 3 and 6 ^ 3 give?

Show answer

In binary 6 is 110 and 3 is 011. AND gives 010, which is 2; OR gives 111, which is 7; XOR gives 101, which is 5.

4. Use a shift to calculate 2 ** 8.

Show answer

1 << 8, which is 256.

5. Write a test that is True when n is odd, using &.

Show answer

n & 1 == 1, or with brackets (n & 1) == 1.

6. What is ~9?

Show answer

-10, because ~x is -(x + 1).