Reputation: 763
Simple question, but I can't quite seem to figure it out:
If i have an integer, say 12, and I perform the following bit-manipulation on it:
int i = 12;
i = (i << 3) + (i << 1);
I end up with 120 (12*10). This is the case with any number.
Can someone explain to me, succinctly, why it is that this works? (I'm obviously missing something quite rudimentary when it comes to bitshifting).
Upvotes: 21
Views: 15031
Reputation: 8511
Left bitshift is the same (usually) as multiplying by power's of two. i.e. << 1
is equivalent to *(2^1)
, << 2
is equivalent to *(2^2)
and so on...
If you substitute that into your example you can see why your result is multiplied by 10:
int i = 12;
i = (i * 2^3) + (i * 2^1);
= { i = (i * 8) + (i * 2);}
= { i = 8i + 2i; }
= { i = 10i; }
Upvotes: 1
Reputation: 2044
i << 3
is equivalent to i * 8
. i << 1
is equivalent to i * 2
.
The distribute property tells us that:
x = i * 10
x = i * (8 + 2)
x = 8i + 2i
Upvotes: 5
Reputation: 4484
Shifting left by 3 places is equal to multiplying by 8, shifting by 1 places is equal to multiplying by 2 so you are doing
i = i * 8 + i * 2
Upvotes: 1
Reputation: 272447
Rewrite the bitshifts as multiplications by powers-of-2, and all should become clear.
Upvotes: -1
Reputation: 146900
Express as multiplication.
i = (i << 3) + (i << 1);
i = (i * 8) + (i * 2);
i = 8i + 2i
i = 10i
Upvotes: 33