How to do unsigned saturating addition in C?

前端 未结 17 1881
孤独总比滥情好
孤独总比滥情好 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
    2020-11-27 03:06

    //function-like macro to add signed vals, 
    //then test for overlow and clamp to max if required
    #define SATURATE_ADD(a,b,val)  ( {\
    if( (a>=0) && (b>=0) )\
    {\
        val = a + b;\
        if (val < 0) {val=0x7fffffff;}\
    }\
    else if( (a<=0) && (b<=0) )\
    {\
        val = a + b;\
        if (val > 0) {val=-1*0x7fffffff;}\
    }\
    else\
    {\
        val = a + b;\
    }\
    })
    

    I did a quick test and seems to work, but not extensively bashed it yet! This works with SIGNED 32 bit. op : the editor used on the web page does not let me post a macro ie its not understanding non-indented syntax etc!

提交回复
热议问题