Search code examples
cbit-manipulationbitwise-operators

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


Solution

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

    So the line should be...

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