Search code examples
c++cperformanceinteger-division

How to divide unsigned integer of 256 and round to the closer value?


I need to divide number of 256 and round it to closer value, for example, if input 255 I want to get 1, not 0. Now I'm using

int x = 150;
int z = MulDiv(x, 1, 256);

But I think it is not optimal way to reach my goal, can someone advice better way.


Solution

  • Use this:

    unsigned int x = 150;
    unsigned int z = (x + 128) >> 8;
    

    128 is middle value, so it after adding this your rounding works, and 256=2^8 so you can use bit shift operation instead of division.

    NOTE: this way works for only positive values.

    If you need this for positive and negative values you will need this:

    int x = -150;
    int z = (x >= 0 ? (x + 128) : (x - 128)) / 256;
    

    NOTE: bit-shifting for signed values has some specific and not always can be trusted so you cannot use this: int z = (x < 0) ? (x - 128) / 256 : (x + 128) >> 8;