How to subtract two unsigned ints with wrap around or overflow

后端 未结 8 2043
星月不相逢
星月不相逢 2020-12-08 21:07

There are two unsigned ints (x and y) that need to be subtracted. x is always larger than y. However, both x and y can wrap around; for example, if they were both bytes, af

8条回答
  •  星月不相逢
    2020-12-08 21:51

    The problem should be stated as follows:

    Let's assume the position (angle) of two pointers a and b of a clock is given by an uint8_t. The whole circumerence is devided into the 256 values of an uint8_t. How can the smaller distance between the two pointer be calculated efficiently?

    A solution is:

    uint8_t smaller_distance = abs( (int8_t)( a - b ) );

    I suspect there is nothing more effient as otherwise there would be something more efficient than abs().

提交回复
热议问题