(no title)
noasaservice | 3 years ago
min(x, y)+( ((unsigned int)abs(x-y))>>1);
with no issue.
abs(x-y)is the distance between points x and y. We don't care about order here because of the absolute value. And by its nature, it will always be positive - hence unsigned.
We divide the distance between the points by 2. This always provides a solution that fits in the signed bounds of X and Y once you add to min(x,y).
And it costs an ABS, a subtract, a non-negative bitshift, and a min().
To make it more complete, a switch statement depending on type of input function would be needed to handle the various sizes of numbers. And then it'd be doing the same but for long int->unsigned long int etc.
MaxBarraclough|3 years ago
The subtraction can overflow, e.g. INT_MIN - 1, or 0 - INT_MIN. The abs call can also overflow, with abs(INT_MIN). In both cases, the overflow causes undefined behaviour.
To calculate the difference between 2 signed integers we must bear in mind that the result may exceed INT_MAX, and must use unsigned int for the result. I wrote about this on StackOverflow: https://stackoverflow.com/q/10589559