Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifting to multiply an integer by 10

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).

like image 301
Jack Smith Avatar asked May 25 '12 16:05

Jack Smith


1 Answers

Express as multiplication.

i = (i << 3) + (i << 1);
i = (i * 8) + (i * 2);
i = 8i + 2i
i = 10i
like image 80
Puppy Avatar answered Oct 01 '22 09:10

Puppy