1

In C I have this enum:

enum {
    STAR_NONE =     1 << 0, // 1
    STAR_ONE =      1 << 1, // 2
    STAR_TWO =      1 << 2, // 4
    STAR_THREE =    1 << 3  // 8
};

Why is 1 << 3 equal to 8 and not 6?

  • 8
    Why is `1 << 2` equal to 4 and not 3? – Robert Harvey Feb 08 '15 at 15:55
  • 5
    You input `3 << 1` into that bitshift calculator website, not `1 << 3`. –  Feb 08 '15 at 15:56
  • 1
    Left shifting a number by x bits is nothing but multiplying the number by (2^x) and right shifting by x bits is dividing by (2^x)! Additional info: That's why many times bit shifting is used instead of Multiplication and Division for faster operation! – Swanand Feb 08 '15 at 16:02
  • @Swanand That formula made everything a thousand times more clear, thanks –  Feb 08 '15 at 16:03
  • @LightnessRacesinOrbit Maybe this sounds stupid but I thought because 3 << 1 = 6, the other way around too –  Feb 08 '15 at 17:46
  • 1
    @YassineHoussni: You're right; it does ;) It's best to _research_ and _understand_ what things do, rather than wildly guessing. – Lightness Races in Orbit Feb 08 '15 at 17:50
  • @LightnessRacesinOrbit lol! Yeah, I am completely new to bitshifting, I just started researchen, I've never used it before but now I took the step to learn about it. –  Feb 08 '15 at 17:55

4 Answers4

7

Shifting a number to the left is equivalent to multiplying that number by 2n where n is the distance you shifted that number.

To see how is that true lets take an example, suppose we have the number 5 so we shift it 2 places to the left, 5 in binary is 00000101 i.e.

0×27 + 0×26 + 0×25 + 0×24 + 0×23 + 1×22 + 0×21 + 1×20 = 1×22 + 1×20 = 4 + 1 = 5

now, 5 << 2 would be 00010100 i.e.

0×27 + 0×26 + 0×25 + 1×24 + 0×23 + 1×22 + 0×21 + 0×20 = 1×24 + 1×22 = 16 + 4 = 20

But we can write 1×24 + 1×22 as

1×24 + 1×22 = (1×22 + 1×20)×22 = 5×4 → 20

and from this, it is possible to conclude that 5 << 2 is equivalent to 5×22, it would be possible to demonstrate that in general

k << m = k×2m

So in your case 1 << 3 is equivalent to 23 = 8, since

1 << 3b00000001 << 3b00001000 → 23 -> 8

If you instead did this 3 << 1 then

3 << 1b00000011 << 1b00000110 → 22 + 21 → 4 + 2 → 6

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Sometimes [terseness](http://stackoverflow.com/a/28396041/2410359) beats completeness - like your fine complete answer. – chux - Reinstate Monica Feb 08 '15 at 16:47
  • @chux not this time. Thanks iharob for the answer, this is exactly what I needed to get a clear view about shifting. –  Feb 08 '15 at 17:36
3

1 in binary is 0000 0001

by shifting to left by 3 bits (i.e. 1 << 3) you get

0000 1000

Which is 8 in decimal and not 6.

SMA
  • 36,381
  • 8
  • 49
  • 73
1

Because two to the power of three is eight.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
1

Think in binary. You are actually doing this. 0001 shifted 3 times to the left = 1000 = 8

JDWK
  • 51
  • 5