Search code examples
cbinarybitwise-operatorsbit-shift

Left shift gives me strange results


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    printf("left shift 1 = %d\n", 1 << 1);
    printf("left shift 2 = %d\n", 1 << 2);
    printf("left shift 3 = %d\n", 1 << 3);
    printf("left shift 4 = %d\n", 1 << 4);
    printf("left shift 5 = %d\n", 1 << 5);
    printf("left shift 6 = %d\n", 1 << 6);
    printf("left shift 7 = %d\n", 1 << 7);

    return 0;
}

and I got the output like this:

left shift 1 = 2
left shift 2 = 4
left shift 3 = 8
left shift 4 = 16
left shift 5 = 32
left shift 6 = 64
left shift 7 = 128

It seem correct for number 1 and 2, but what happened to other numbers from 3 to 7?


Solution

  • The left shift operation n << 1 in fact multiplies the left operand by 2. And the result of your program shows this.

    Let's assume that you have an object named n of the type char:

    0000 0001
    

    then n << 1 gives:

    0000 0010 
    

    that in the decimal notation is 2:

    n << 2 gives

    0000 0100
    

    that in the decimal notation is 4:

    n << 3 gives

    0000 1000
    

    that is the decimal notation is 8.

    And so on.