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

后端 未结 10 929
情书的邮戳
情书的邮戳 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条回答
  •  猫巷女王i
    2020-12-07 19:29

    In C++20, you can use std::midpoint:

    template 
    constexpr T midpoint(T a, T b) noexcept;
    

    The paper P0811R3 that introduced std::midpoint recommended this snippet (slightly adopted to work with C++11):

    #include 
    
    template 
    constexpr Integer midpoint(Integer a, Integer b) noexcept {
      using U = std::make_unsigned::type;
      return a>b ? a-(U(a)-b)/2 : a+(U(b)-a)/2;
    }
    

    For completeness, here is the unmodified C++20 implementation from the paper:

    constexpr Integer midpoint(Integer a, Integer b) noexcept {
      using U = make_unsigned_t;
      return a>b ? a-(U(a)-b)/2 : a+(U(b)-a)/2;
    }
    

提交回复
热议问题