Re:Fast midpoint between two integers without overflow
by bonzini on Wednesday December 07, 2022 @10:21AM
(#33895338)
It's still wrong for signed integers if a/2 rounds towards zero. You need a>>1 and b>>1.
Re:Fast midpoint between two integers without overflow
by nick4780167 on Wednesday December 07, 2022 @10:17AM
(#33895282)
Maybe a little slower, but way more readable than the ones in the article.
"This will be too low if the original addition contained a carry from bit 0 to bit 1, which happens if bit 0 is set in both of the terms, so we detect that case and make the necessary adjustment."
return (a / 2) + (b / 2) + (a & b & 1);