How to subtract two unsigned ints with wrap around or overflow

后端 未结 8 2010
星月不相逢
星月不相逢 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

    To echo everyone else replying, if you just subtract the two and interpret the result as unsigned you'll be fine.

    Unless you have an explicit counterexample.

    Your example of x = 0x2, y= 0x14 would not result in 0x4, it would result in 0xEE, unless you have more constraints on the math that are unstated.

    0 讨论(0)
  • 2020-12-08 21:52

    Just to put the already correct answer into code:

    If you know that x is the smaller value, the following calculation just works:

    int main()
    {
        uint8_t x = 0xff;
        uint8_t y = x + 20;
        uint8_t res = y - x;
        printf("Expect 20: %d\n", res); // res is 20
    
        return 0;
    }
    

    If you do not know which one is smaller:

    int main()
    {
        uint8_t x = 0xff;
        uint8_t y = x + 20;
        int8_t res1 = (int8_t)x - y;
        int8_t res2 = (int8_t)y - x;
        printf("Expect -20 and 20: %d and %d\n", res1, res2);
    
        return 0;
    }
    

    Where the difference must be inside the range of uint8_t in this case.

    The code experiment helped me to understand the solution better.

    0 讨论(0)
提交回复
热议问题