I have been stuck on this bitwise puzzle for a few hours. I was searching for a good solution to this problem on google to see how others were solving it and i came across this solution. I am trying to figure out how it works. The only thing i don't understand about this is the rounding process and the lost bits? what bits are lost?
I would really appreciate someone explaining this solution to me.
Thanks in advance guys, Yosemite :)
/*
* ezThreeFourths - multiplies by 3/4 rounding toward 0,
* Should exactly duplicate effect of C expression (x*3/4),
* including overflow behavior.
* Examples: ezThreeFourths(11) = 8
* ezThreeFourths(-9) = -6
* ezThreeFourths(1073741824) = -268435456 (overflow)
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 3
*/
int ezThreeFourths(int x) {
/*
*sets y to make up for the lost bits while rounding. Multiplies
*by three by adding x 3 times. Records the sign since
* what is added will be different depending on whether the sign
*is positive or negative and adds this to to the number. Then
*divedes by 8 by shifting.
*/
int y = 3;
x =x+x+x;
int z = x>>31;
z = y & z;
x = z + x;
x = x>>2;
return x;
}
this is the link where i got it from: link the individual didn't mark his name in the file so i don't know his name