How to do unsigned saturating addition in C?

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

    I suppose, the best way for x86 is to use inline assembler to check overflow flag after addition. Something like:

    add eax, ebx
    jno @@1
    or eax, 0FFFFFFFFh
    @@1:
    .......
    

    It's not very portable, but IMHO the most efficient way.

提交回复
热议问题