How can I safely average two unsigned ints in C++?

后端 未结 10 937
情书的邮戳
情书的邮戳 2020-12-07 19:05

Using integer math alone, I\'d like to \"safely\" average two unsigned ints in C++.

What I mean by \"safely\" is avoiding overflows (and anything else that can be th

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 19:25

    What you have is fine, with the minor detail that it will claim that the average of 3 and 3 is 2. I'm guessing that you don't want that; fortunately, there's an easy fix:

    unsigned int average = a/2 + b/2 + (a & b & 1);
    

    This just bumps the average back up in the case that both divisions were truncated.

提交回复
热议问题