Right shifting of positive integers leads to truncation:

9 >> 149 >> 22

Interestingly, right shift for negative integers also leads to truncation:

-9 >> 1-5-9 >> 2-3

If we combine the effects, we can get rounding up during right shift for positive integers:

-(-9 >> 1)5-(-9 >> 2)3

So here is a C function for rounding up while shifting:

int rightShiftRoundUp(int x, int n){return - ( -x >> n);}

Voila!

## No comments:

Post a Comment