CodeBlanks Logo Icon CodeBlanks

Bit shifting

  • C course
  • Intermediate
  • Lesson 102/116
  • 5 min

Learn bit shifting patterns with << and >>.

Bit shifting

Bit shifting moves a value's bits left (<<) or right (>>). Left shift moves every bit one position up; it is equivalent to multiplying by a power of two.

Example: 1 << 4 gives 16; shifting 1 four places left yields sixteen. Similarly 256 >> 2 gives 64; shifting right two places is equivalent to dividing by four. For unsigned types, right shift always fills with zeros; for signed types the sign bit may be preserved. Shifting is a core tool for separating color channels and bit packing.

Shifts and powers of two

Shifting is the fast way to multiply and divide by powers of two. n << k means n * 2^k; n >> k means n / 2^k (integer division).

Example: 1 << 4 = 16 (1 × 2⁴), 256 >> 2 = 64 (256 ÷ 4). CPUs do it faster than multiplication, so old code used it for performance. Modern compilers turn n * 4 into n << 2 automatically; so today multiplication is preferred for readability. But in bit packing, shifting is still essential; it is the only way to place bits at the right position.

Practice Write a bit shifting program

Declare unsigned int x = 1;. Print with printf("%u\n", x << 4); to shift left. Declare unsigned int y = 256;. Print with printf("%u\n", y >> 2); to shift right.

Starter code

main.c
#include <stdio.h>

// Define x as 1
// Shift left and print
// Define y as 256
// Shift right and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    unsigned int x = 1;
    printf("%u\n", x << 4);
    unsigned int y = 256;
    printf("%u\n", y >> 2);
    return 0;
}

Expected output

16
64

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the left shift expression

Question
printf("%u
", x << ____);
Answer
printf("%u
", x << 4);

Explanation: x << 4 is equivalent to multiplying by sixteen.

2 Match the shift operations

Term Meaning
<< Shift left
>> Shift right
1 << 4 Sixteen
256 >> 2 Sixty four

3 What is 1 << 4?

  • 4
  • 16 Correct answer
  • 8
  • 32

Explanation: Shifting 1 four places left gives 16 (2⁴).

All lessons in Intermediate