I need to multiply the number by 3/16, rounding to zero using only bitwise operations like ! ~ & ^ | + << >>. So far I have the following: the only problem is that it does not work when the number is negative, it is always rounded, not zero. I know there should be a bitwise if statement, if x is negative, then add 15. But I donβt know how to implement it, any help is appreciated.
int ezThreeSixteenths(int x) {
int times_two = x << 1;
int times_three = times_two + x;
int divide_eight = times_three >> 4;
int a = 0b11111111;
int a1 = a << 8;
int a2 = a << 16;
int a3 = 0b11111 << 24;
int mask = a | a1 | a2 | a3;
int final = divide_eight & mask;
return final;
}
source
share