How to do unsigned saturating addition in C?

前端 未结 17 1808
孤独总比滥情好
孤独总比滥情好 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:02

    uint32_t saturate_add32(uint32_t a, uint32_t b)
    {
        uint32_t sum = a + b;
        if ((sum < a) || (sum < b))
            return ~((uint32_t)0);
        else
            return sum;
    } /* saturate_add32 */
    
    uint16_t saturate_add16(uint16_t a, uint16_t b)
    {
        uint16_t sum = a + b;
        if ((sum < a) || (sum < b))
            return ~((uint16_t)0);
        else
            return sum;
    } /* saturate_add16 */
    

    Edit: Now that you've posted your version, I'm not sure mine is any cleaner/better/more efficient/more studly.

提交回复
热议问题