Leo_Wang
Leo_Wang

Reputation: 67

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?

Upvotes: 0

Views: 200

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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.

Upvotes: 0

Roberto Caboni
Roberto Caboni

Reputation: 7490

What you experience is the correct behavior of the shifting operator.

Let's start from illustrating the decimal representation of a byte:

ByteDecValue = 
    bit0 * 2^0 +
    bit1 * 2^1 +
    bit2 * 2^2 +
    bit3 * 2^3 +
    bit4 * 2^4 +
    bit5 * 2^5 +
    bit6 * 2^6 +
    bit7 * 2^7

So, for example, the decimal value corresponding to the byte 00010010b is 2^4 + 2^1 = 18 dec.

An interesting particular scenario occurs when only one byte is 1. Deriving the formula from the one above we can say

ByteDecValue_bit_N = 2^N

2^0 = 1 << 0 = 0000 0001
2^1 = 1 << 1 = 0000 0010
2^2 = 1 << 2 = 0000 0100
2^3 = 1 << 3 = 0000 1000
2^4 = 1 << 4 = 0001 0000
2^5 = 1 << 5 = 0010 0000
2^6 = 1 << 6 = 0100 0000
2^7 = 1 << 7 = 1000 0000

That's exactly what you experience: by shifting 1 to the left N times you get a single 1 in position N, so the power 2^N.

Note: your test would have been complete by printing also the value of 1 << 0. In that case you would have got 2^0 = 1. No shift at all means keeping the original value.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881443

There's nothing strange about that at all. For an unsigned integer (also usually for a signed integer where you don't encroach on the sign bit, but this is not mandated by the standard), a left shift is basically a doubling of the value.

And that's exactly what you're seeing:

1 << 0 = 0000 0001 =   1
1 << 1 = 0000 0010 =   2
1 << 2 = 0000 0100 =   4
1 << 3 = 0000 1000 =   8
1 << 4 = 0001 0000 =  16
1 << 5 = 0010 0000 =  32
1 << 6 = 0100 0000 =  64
1 << 7 = 1000 0000 = 128

Upvotes: 1

Related Questions