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?
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?
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 << 3
→ b00000001 << 3
→ b00001000
→ 23 -> 8
If you instead did this 3 << 1
then
3 << 1
→ b00000011 << 1
→ b00000110
→ 22 + 21 → 4 + 2 → 6
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.
Think in binary. You are actually doing this. 0001 shifted 3 times to the left = 1000 = 8