How to do unsigned saturating addition in C?

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

    The best performance will usually involve inline assembly (as some have already stated).

    But for portable C, these functions only involve one comparison and no type-casting (and thus I believe optimal):

    unsigned saturate_add_uint(unsigned x, unsigned y)
    {
        if (y > UINT_MAX - x) return UINT_MAX;
        return x + y;
    }
    
    unsigned short saturate_add_ushort(unsigned short x, unsigned short y)
    {
        if (y > USHRT_MAX - x) return USHRT_MAX;
        return x + y;
    }
    

    As macros, they become:

    SATURATE_ADD_UINT(x, y) (((y)>UINT_MAX-(x)) ? UINT_MAX : ((x)+(y)))
    SATURATE_ADD_USHORT(x, y) (((y)>SHRT_MAX-(x)) ? USHRT_MAX : ((x)+(y)))
    

    I leave versions for 'unsigned long' and 'unsigned long long' as an exercise to the reader. ;-)

提交回复
热议问题