How to do unsigned saturating addition in C?

前端 未结 17 1872
孤独总比滥情好
孤独总比滥情好 2020-11-27 02:31

What is the best (cleanest, most efficient) way to write saturating addition in C?

The function or macro should add two unsigned inputs (need both 16- and 32-bit ver

17条回答
  •  半阙折子戏
    2020-11-27 03:09

    In plain C:

    uint16_t sadd16(uint16_t a, uint16_t b) {
      return (a > 0xFFFF - b) ? 0xFFFF : a + b;
    }
         
    uint32_t sadd32(uint32_t a, uint32_t b) {
      return (a > 0xFFFFFFFF - b) ? 0xFFFFFFFF : a + b;
    }
    

    which is almost macro-ized and directly conveys the meaning.

提交回复
热议问题