Hacker News new | ask | show | jobs
by mnaydin 2663 days ago
The proposed solution for C and C++

  mid = ((unsigned int)low + (unsigned int)high)) >> 1;
in the blog may still be wrong if the sum ((unsigned)low + (unsigned)high)) produces a carry.
1 comments

Max 32-bit signed int is (1<<31)-1 . Twice that is 1<<32-2.

Max 32-bit unsigned int is (1<<32)-1.

Therefore, if 'low' and 'high' are non-negative 32-bit signed integers, it is impossible for their sum, when the values are first cast to 32-bit unsigned integers, to produce a carry.

True. I had thought low and high could be unsigned originally, in which case casting to unsigned is redundant, then the sum would produce a carry.