Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bitwise operation to multiply by 3

Very basic question that is tripping me up: Write a function that produces the same thing as this:

int mult_3_div_4(int x){return (x*3)/4;}

But only using ! ~ & + << >> bitwise operators

Divide by 4 is of course << 2 So I tried something like:

int test(int x) {return ((x<<1 + x) >> 2);}

But I can't seem to find anything that matches x*3 using bitwise operators

like image 325
Max Jones Avatar asked Mar 03 '23 05:03

Max Jones


1 Answers

The bitwise shifts << >> have lower precedence that binary operators + -.

So the line should be...

int test(int x) {return ((x<<1) + x) >> 2;}
like image 114
Lily AB Avatar answered Mar 12 '23 03:03

Lily AB