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

后端 未结 10 928
情书的邮戳
情书的邮戳 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:38

    Your method is not correct if both numbers are odd eg 5 and 7, average is 6 but your method #3 returns 5.

    Try this:

    average = (a>>1) + (b>>1) + (a & b & 1)
    

    with math operators only:

    average = a/2 + b/2 + (a%2) * (b%2)
    

提交回复
热议问题