Sunday, August 14, 2011

Rounding up!

Right shifting of positive integers leads to truncation:

9 >> 1
4
9 >> 2
2

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: