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

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

    unsigned int average = low + ((high - low) / 2);
    

    EDIT

    Here's a related article: http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html

提交回复
热议问题