News for hackers. Stuff that matters.
Re:Finding the average of two unsigned integers without over... by nonsequitur on Tuesday February 08, 2022 @07:02AM (#30257450)
This doesn't work because you're not left-shifting (doubling) the carry. But when adding the shifted carry to (x ^ y) we're back to potentially overflowing the highest bits. The solution is to add the highest and the lower bits separately:

  lower = 0x7f7f7f7f;
  highest = ~lower;
  z = ((x & lower) + (y & lower)) ^ ((x ^ y) & highest);
Note this only improves performance for larger container integers.
Re:Finding the average of two unsigned integers without over... by rustybolt on Wednesday February 09, 2022 @01:49AM (#30269723)
You're completely right! Typically you don't care about overflow though (and you should use unsigned ints to avoid undefined behavior).