do multiple by a float type number using only shifting and adding

646 views Asked by At

How can I execute multiplication by 2.75 using only shifting and adding? I know multiple by 2 is done by bit shifting 1<

2

There are 2 answers

4
Paul R On

Assuming you want to multiply an int by a non-integer constant such as 2.75, then you can just break this down as:

y = x * 2 + x / 2 + x / 4; // y = 2x + 0.5x + 0.25x

which can be expressed using shifts and adds as:

y = (x << 1) + (x >> 1) + (x >> 2);
2
chux - Reinstate Monica On

To multiply by 2 simply left shift.

y = (x << 1) + ...;

To multiply by 0.75, multiply by 3 and divide by 4 (shift right 2). Consider the value of x==3. This results in y==2. The math of 3*0.75 is 2.25. With (x >> 1) + (x >> 2), the result would be 1.

y = ... + (x+x+x >> 4);

To get a rounded value (assuming positive numbers), add 1/2 the divisor (which is 4 in this case) prior to dividing/right-shifting.

y = ... + (x+x+x + 2) >> 2;

All together:

// y = x*2.75
y = (x << 1) + ((x+x+x + 2) >> 2);