Bit Manipulation Basics

What is Bit Manipulation?

Operating on individual bits inside binary numbers.

You’ve already seen XOR. Here are the other common operations.


AND

Both bits must be 1 to get 1.

AABBABA \land B
000
010
100
111

Only 1 AND 1 gives 1. Everything else is 0.


Example:

10111100=10001011 \land 1100 = 1000

Compare each column. Both 1? Keep it. Otherwise, 0.


OR

Either bit being 1 gives 1.

AABBABA \lor B
000
011
101
111

Only 0 OR 0 gives 0. Everything else is 1.


Example:

10111100=11111011 \lor 1100 = 1111


NOT

Flip every bit.

¬1011=0100\lnot 1011 = 0100

1 becomes 0. 0 becomes 1.


Left Shift

Move all bits to the left. Fill the right with 0.

10111=101101011 \ll 1 = 10110

10112=1011001011 \ll 2 = 101100

Each left shift multiplies by 2.


Right Shift

Move all bits to the right. Bits on the right fall off.

10111=1011011 \gg 1 = 101

10112=101011 \gg 2 = 10

Each right shift divides by 2 (drops remainder).


Quick Reference

OperationSymbolWhat it does
AND\land1 only if both are 1
OR\lor1 if either is 1
XOR\oplus1 if different
NOT¬\lnotFlip all bits
Left shift\llMultiply by 2
Right shift\ggDivide by 2