Let us say that I ask you to find the number I am thinking about between -1000 and 1000, by repeatedly guessing a number. With each guess, I tell you whether your guess is correct, smaller or larger than my number. A binary search algorithm tries to find a value in an interval by repeating finding the midpoint, using smaller and smaller intervals. You might start with 0, then use either -500 or 500 and so forth.

Thus we sometimes need a fast algorithm to find the midpoint in an interval of integers.The following simple routine to find the midpoint is incorrect:

int f(int x, int y) { return (x + y)/2; }

If the integers use a 64-bit two’s complement representation, we could pick 1 for x and 9223372036854775807 for y, and then the result of the function could be a large negative value.

Efficient solutions are provided by Warren in Hacker’s Delight (section 2.5):

int f(int x, int y) { return (x|y) - ((x^y)>>1); }

int f(int x, int y) { return ((x^y)>>1) + (x&y); }

They provide respectively the smallest value no smaller than (x+y)/2 and the largest value no larger than (x+y)/2. The difference between the two values is `(x ^ y) & 1` (credit: Harold Aptroot).

They follow from the following identities: `x+y=(x^y)+2*(x&y)` and `x+y=2*(x|y)-(x^y)`.

**Update**: Reader BartekF observes that C++20 added a dedicated function for this problem: std::midpoint.

Daniel Lemire, "Fast midpoint between two integers without overflow," in *Daniel Lemire's blog*, December 6, 2022.

`((x^y)>>1) + (x&y)`

is 4 operations. Whereas`x + (y-x)>>1`

is only 3 operations (and has the same span). Am I missing something?nevermind, the given algorithms are commutative

`y-x` can overflow when operating on signed integers, which is UB is C/C++.

you can also compare it with a C++20’s addition: std::midpoint from

Just linking to the various implementations of std::midpoint in various compilers

GCC – https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/include/std/numeric;h=0f1f26cd0c456f9bd1eb2fd6b2e7fd686a8a50e6;hb=refs/heads/trunk#l206

LLVM Clang – https://github.com/llvm/llvm-project/blob/main/libcxx/include/__numeric/midpoint.h

MSVC STD – https://github.com/microsoft/STL/blob/main/stl/inc/numeric#L651

It is kind of sad that not a single compiler implemented an optimal template specialization for std::midpoint.

Update: after reading cppreference now I see why: unlike optimized versions, std::midpoint provides very specific requirements for rounding, which are not supported by optimized versions.

(int)(x + y)*.5

EVERY properly written optimising compiler SHOULD emit code like

for this function.

If the target processor lacks the equivalent of the RCR (Rotate through carry right) instruction, but has a ROR (Rotate right) instruction, it can emit

instead.

RCR is an appealing solution but, on some processors, it is significantly more expensive than a simple shift.

That’s the other reason why I mentioned to substitute it by ADC/ROR

ALSO: RCR is (if available) ALWAYS less expensive than the “pure” C formula/expression.

I think the example with 1 and 9223372036854775807 doesn’t demonstrate the problem: the problem is negative numbers, otherwise one can always do (uint) (x + y) >> 1.

If you only have positive integers, and you are using a two’s complement signed type, then I agree that you can always work around overflows with relative ease. I did not make this assumption.

Actually, it still contains a possible overflow. You need to cast before the addition.

It doesn’t matter, actually. The addition works exactly the same for signed and unsigned types in two’s complement representation. The cast is needed to perform the unsigned bit shift which doesn’t preserve the sign (unlike the signed shift). In some sense the signed addition of non-negative values overflows to the sign bit, then we interpret the result as unsigned and do the unsigned division by 2.

That’s still an overflow though.

You may say that the overflow, if it is not trapped, may be ignored, and you will be right because modern C/C++ and most other systems rely on two’s complement. However, it is still, by definition, an overflow.

You are right guys. Today I learned that

signedinteger overflow behavior is undefined in C(++). Sorry for inconvenience.For historical context: The first publicly stated instance of the second formula that I am aware of appeared in a post by Peter L. Montgomery in newsgroup comp.arch on 2000/02/11; see

https://groups.google.com/d/msg/comp.arch/gXFuGZtZKag/_5yrz2zDbe4J:

”

If XOR is available, then this can be used to average

two unsigned variables A and B when the sum might overflow:

(A+B)/2 = (A AND B) + (A XOR B)/2

“