# Neater way to multiply many times

I needed to find away to left shift a number on a platform with buggy `<<` and `>>` bitwise operators. I came up with a rudimentary solution, but it looks ugly and inefficient. What's a better way to do this?

``````float leftShift8(int value) {
return value * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
}

float rightShift8(int value) {
return value / 2 / 2 / 2 / 2 / 2 / 2 / 2 / 2;
}
``````
-
buggy shift operators? Are you sure? That sounds very suspect. –  Winston Ewert Aug 5 '12 at 14:05
just joking. the actual matter is more complicated so I used that as a justification. –  Geotarget Aug 5 '12 at 14:13

Why wouldn't you do something like

``````float rightShift(int value, int numberOfShift)
{
float result = (float)value;
while(numberOfShift-- > 0)
value*=2.0f;
return value;
}

float leftShift(int value, int numberOfShift)
{
float result = (float)value;
while(numberOfShift-- > 0)
value/=2.0f;
return value;
}
``````

This would especially deal with the fact that you do not return int type, but float. Additionally, its a lot faster to do a 2*2*2 than pow(2,3)

-
Multiplying is not faster in C++, the difference in only noticable in C. See this thread: stackoverflow.com/questions/2940367/…. –  Jean-François Côté Aug 6 '12 at 17:49
In c++ it doesn't make a noticeable difference. And Jean-François' code is much simpler easier to the programmer to read –  Goldorak84 Aug 6 '12 at 18:10

If I understand well, you are using a computer that have "broken" bitwise operators? That is odd but maybe you can try this?

``````float leftShit8(int value)
{
return pow(2, 8) * value;
}
``````

This code simply do a power of 8 on the base that is 2. After that, you multiply by your value. It does the same thing as your code but I'm not sure why anyone would use this instead of bitwise since bitwise a much more faster I think.

You could make this more general and useful like this

``````float leftShit(int value, int numberOfShift)
{
return pow(2, numberOfShift) * value;
}
``````

EDIT: For the edited question about division, the is only a sligh change. Thanks to T.C for this (answer below), I include it in my answer to make it more complete

``````float rightShift(int value, int numberOfShift)
{
return value/pow(2, numberOfShift);
}
``````

Anyway, I hope it will help.

-
Great Jaff, thanks a ton, but can you solve the divide problem as well? Updated question. –  Geotarget Aug 5 '12 at 14:19
`leftShit` -> `leftShift` –  luiscubal Aug 5 '12 at 16:27

Well, going on Jean-François's answer above, to solve the division:

``````float rightShift(int value, int numberOfShift)
{
return value/pow(2, numberOfShift);
}
``````

Again, there you go.

-
Thanks for this, I added it to my answer :) –  Jean-François Côté Aug 6 '12 at 18:05