Skip to content
CodeItRaw
Bit Manipulation

Lesson 1/3

A computer keeps every number in base two, in bits: 6 is 110 (4 + 2) and 3 is 011 (2 + 1). Bit operations compare the bits of two numbers at the same position: & (and) gives 1 if both are 1; | (or) if at least one is; ^ (exclusive or, XOR) if they differ.

a, b = 12, 10 # 1100, 1010
a & b # 1000 -> 8
a | b # 1110 -> 14
a ^ b # 0110 -> 6
a << 1 # 11000 -> 24
a >> 2 # 11 -> 3
<< shifts the bits left; each shift multiplies the number by two. >> shifts right; each shift halves it and drops the rightmost bit. To find a result in your head, write the two numbers one under the other in binary.

Two small pieces are useful everywhere. n & 1 is the number's rightmost bit (odd or even). n >> 1 drops that bit. Put the two in a loop and you read a number's bits from right to left one at a time: look at the rightmost, drop it, repeat; when the number is 0 you are done.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Bit Operators

    Code reading · Predict the Output

  2. 02

    Count the Ones

    Code reading · Bug Hunt

If you would rather not wait for the order, every problem is open without locks: Problem list