How to do unsigned saturating addition in C?

前端 未结 17 1867
孤独总比滥情好
孤独总比滥情好 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 03:00

    Just in case someone wants to know an implementation without branching using 2's complement 32bit integers.

    Warning! This code uses the undefined operation: "shift right by -1" and therefore exploits the property of the Intel Pentium SAL instruction to mask the count operand to 5 bits.

    int32_t sadd(int32_t a, int32_t b){
        int32_t sum = a+b;
        int32_t overflow = ((a^sum)&(b^sum))>>31;
        return (overflow<<31)^(sum>>overflow);
     }
    

    It's the best implementation known to me

提交回复
热议问题