What is the right way to find the average of two values?

后端 未结 8 1137
北荒
北荒 2021-02-19 00:58

I recently learned that integer overflow is an undefined behavior in C (side question - is it also UB in C++?)

Often in C programming you need to find the average of two

8条回答
  •  执念已碎
    2021-02-19 01:11

    If you only have to deal with unsigned integer types (and can think in binary), you can decompose your addition into digit and carry. We can write a+b (in unlimited precision) as (a^b) + ((a&b)<<1)), so (a+b)/2 is simply ((a^b)>>1) + (a&b). This last expression fits within the common type of a and b, so you can use it in your code:

    unsigned semisum(unsigned a, unsigned b)
    {
        return ((a^b)>>1) + (a&b);
    }
    

提交回复
热议问题