Bit Manipulation Basics

Every number inside a computer is really just a row of 0s and 1s. We call each of those 0s and 1s a bit, which is short for binary digit. Most of the time you never see those bits. You write 5 and the machine quietly stores it as 101. But sometimes you want to reach in and work on those bits directly. That is what bit manipulation is.

Here is the pain. Say you want to check if a number is even or odd. The normal way uses the remainder. That works. But the computer has to do a division to find the remainder, and division is slow. With bits you can answer the same question by looking at just one bit. It is faster. And it is one short line. So bit manipulation gives you small tricks that run very fast.

In this tutorial we go slow. We define each operator. We show a tiny example. Then we build up the common tricks.

πŸ“š What Is a Bit, Really?

A number in binary is written using only 0 and 1. Each spot in that row is a bit. The rightmost bit is the smallest. Each bit to the left is worth twice as much as the one before it.

Take the number 13. In binary it is 1101. Read it like this.

Bit value 8 4 2 1
13 in bits 1 1 0 1

Add up the spots that have a 1. That is 8 plus 4 plus 1, which gives 13. So 1101 is 13. Good. Now that we can read bits, let us meet the operators that work on them.

πŸ”§ The Bitwise Operators

A bitwise operator is an operator that works on two numbers bit by bit. It lines up the bits of both numbers and decides each result bit on its own. There are a few of them. Each one is simple once you see its little table.

AND (&)

AND looks at one bit from each number. The result bit is 1 only when both input bits are 1. Otherwise it is 0. Think of it as β€œboth must agree.”

a b a AND b
0 0 0
0 1 0
1 0 0
1 1 1

So 6 & 3 lines up 110 and 011. Only the middle bit is 1 in both. The answer is 010, which is 2.

OR (|)

OR gives 1 when at least one of the two bits is 1. It only gives 0 when both are 0. Think of it as β€œeither one is enough.”

a b a OR b
0 0 0
0 1 1
1 0 1
1 1 1

So 6 | 1 lines up 110 and 001. Every spot has at least one 1. The answer comes out 111, which is 7.

XOR (^)

XOR gives 1 when the two bits are different. If they are the same, you get 0. Think of it as β€œspot the difference.”

a b a XOR b
0 0 0
0 1 1
1 0 1
1 1 0

So 6 ^ 3 lines up 110 and 011. The first and last spots differ. The middle is the same. The answer is 101, which is 5.

NOT (~)

NOT works on just one number. It flips every bit. Every 1 becomes 0 and every 0 becomes 1. Because of how computers store negative numbers, ~x ends up equal to -x - 1. So ~5 is -6. That feels strange at first. But it is just every bit flipped.

Left shift (<<) and right shift (>>)

A shift moves all the bits a number of places to the left or to the right.

Left shift moves the bits to the left and fills the empty spots on the right with 0. Each move to the left doubles the number. So 3 shifted left by 1 becomes 6. Shift it by 2 and you get 12.

Right shift moves the bits to the right and drops the bits that fall off the end. Each move to the right halves the number. It throws away any remainder. So 13 shifted right by 1 becomes 6.

Tip

Easy way to remember the arrows. Left shift uses the left-pointing pair and makes numbers bigger. Right shift uses the right-pointing pair and makes numbers smaller.

🎯 Common Bit Tricks

Now the fun part. These are small recipes you will reuse a lot.

The trick to most of them is a mask. A mask is just a number you build with a 1 in the exact spot you care about, and 0s everywhere else. You make a mask for position i by writing 1 << i, which is the number 1 shifted left i times.

Here is what we will do, in plain words first.

  • Check if a number is even or odd. Look at the last bit. If the last bit is 0 the number is even. If it is 1 it is odd. We test it with n & 1.
  • Multiply by 2. Shift left by 1, so n << 1.
  • Divide by 2. Shift right by 1, so n >> 1.
  • Check if a bit is set. β€œSet” means the bit is 1. We make a mask for that spot and AND it with the number. If the result is not 0, the bit was 1.
  • Set a bit. Force a chosen bit to 1. We OR the number with the mask.
  • Clear a bit. Force a chosen bit to 0. We AND the number with a flipped mask.

πŸ§ͺ Steps to Use These Tricks in Code

Let us put every trick into one small program so you can see the output.

Here is the plan the code follows.

  1. Start with the number 13, which is 1101 in bits.
  2. Show AND, OR, and XOR of two numbers.
  3. Check if 13 is odd by testing its last bit.
  4. Double it with a left shift. Halve it with a right shift.
  5. Check whether bit 2 is set in 13. Look at 1101 from the right, counting from 0. Bit 2 is a 1, so it is set.
  6. Set bit 1 to turn 13 into 15.
  7. Clear bit 0 to turn 13 into 12.
bit_tricks.py
def main():
n = 13 # 1101 in binary
# Basic operators
print("6 & 3 =", 6 & 3) # AND
print("6 | 1 =", 6 | 1) # OR
print("6 ^ 3 =", 6 ^ 3) # XOR
# Even or odd: look at the last bit
if (n & 1) == 1:
print(n, "is odd")
else:
print(n, "is even")
# Multiply and divide by 2 using shifts
print("n times 2 =", n << 1)
print("n divided by 2 =", n >> 1)
# Check if bit 2 is set
i = 2
if (n & (1 << i)) != 0:
print("bit", i, "is set")
else:
print("bit", i, "is not set")
# Set bit 1 (13 -> 15)
print("set bit 1 =", n | (1 << 1))
# Clear bit 0 (13 -> 12)
print("clear bit 0 =", n & ~(1 << 0))
main()

The output of the above code will be:

Output
6 & 3 = 2
6 | 1 = 7
6 ^ 3 = 5
13 is odd
n times 2 = 26
n divided by 2 = 6
bit 2 is set
set bit 1 = 15
clear bit 0 = 12

Note

Every one of these tricks is a single step on the bits. The computer does not loop and it does not divide. So each trick runs in O(1) time, which means constant time no matter how big the number is.

πŸ“Š Quick Reference Table

Here are the tricks side by side so you can copy the right one when you need it.

What you want Code Why it works
Is it odd? n & 1 Last bit is 1 only for odd numbers
Multiply by 2 n << 1 Each left shift doubles the number
Divide by 2 n >> 1 Each right shift halves the number
Is bit i set? n & (1 << i) Mask keeps only bit i, rest become 0
Set bit i n | (1 << i) OR forces that one bit to 1
Clear bit i n & ~(1 << i) Flipped mask is 0 only at bit i

⚠️ Common Mistakes

A few traps catch almost everyone at the start. Watch out for these.

  • Mixing up & and &&. The single & is the bitwise operator that works on bits. The double && is the logical AND that works on true and false. Same idea, different jobs. The same warning goes for | and ||.
  • Forgetting that operators have low priority. In many languages & runs after comparison. So n & 1 == 0 is read as n & (1 == 0), which is wrong. Wrap your bit test in parentheses, like (n & 1) == 0.
  • Expecting ~5 to be 5 with the sign removed. NOT flips every bit, so ~5 is -6, not -5. That surprises people.
  • Shifting too far. Shifting a number left by more bits than it can hold gives a result you did not expect. Keep shift amounts small and sensible.
  • Thinking right shift keeps the remainder. It does not. 13 >> 1 is 6, not 6.5. The dropped bit is gone.

🧩 What You’ve Learned

βœ… A bit is one 0 or 1, and every number is just a row of bits.

βœ… AND keeps a bit only when both are 1, OR keeps it when either is 1, and XOR keeps it when the two differ.

βœ… NOT flips every bit, so ~x comes out as -x - 1.

βœ… Left shift doubles a number and right shift halves it.

βœ… You can check, set, and clear any bit using a mask built with 1 << i.

βœ… Every one of these tricks runs in O(1) constant time.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does the expression n & 1 tell you about n?

    Why: The last bit is 1 only for odd numbers, so n & 1 gives 1 when n is odd and 0 when it is even.

  2. 2

    Which operator gives a 1 bit only when the two input bits are different?

    Why: XOR returns 1 when the two bits differ and 0 when they are the same.

  3. 3

    What is the value of 3 << 2?

    Why: Each left shift doubles the number, so shifting 3 left by 2 gives 3 times 4, which is 12.

  4. 4

    How do you set bit i of a number n to 1 without changing the other bits?

    Why: OR with the mask 1 << i forces that one bit to 1 and leaves the rest as they were.

πŸš€ What’s Next?

You now have a handy set of fast bit tricks. Next, keep building your core problem-solving toolkit.

Share & Connect