title: How can I safely average two unsigned ints in C++?
body: <p>Using integer math alone, I'd like to "safely" average two unsigned ints in C++.</p>
  
  <p>What I mean by "safely" is avoiding overflows (and anything else that can be thought of). </p>
  
  <p><b>For instance, averaging <i>200</i> and <i>5000</i> is easy:</b></p>
  
  <pre><code>unsigned int a = 200;
  unsigned int b = 5000;
  unsigned int average = (a + b) / 2; // Equals: 2600 as intended
  </code></pre>
  
  <p><b>But in the case of <i>4294967295</i> and <i>5000</i> then:</b></p>
  
  <pre><code>unsigned int a = 4294967295;
  unsigned int b = 5000;
  unsigned int average = (a + b) / 2; // Equals: 2499 instead of 2147486147
  </code></pre>
  
  <p><b>The best I've come up with is:</b></p>
  
  <pre><code>unsigned int a = 4294967295;
  unsigned int b = 5000;
  unsigned int average = (a / 2) + (b / 2); // Equals: 2147486147 as expected
  </code></pre>
  
  <p>Are there better ways?</p>