How do I programmatically return the max of two integers without using any comparison operators and without using if, else, etc?
max: // Will put MAX(a,b) into a
a -= b;
a &= (~a) >> 31;
a += b;
And:
int a, b;
min: // Will put MIN(a,b) into a
a -= b;
a &= a >> 31;
a += b;
from here.
http://www.graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
r = x - ((x - y) & -(x < y)); // max(x, y)
You can have fun with arithmetically shifting (x - y)
to saturate the sign bit, but this is usually enough. Or you can test the high bit, always fun.
In the math world:
max(a+b) = ( (a+b) + |(a-b)| ) / 2
min(a-b) = ( (a+b) - |(a-b)| ) / 2
Apart from being mathematically correct it is not making assumptions about the bit size as shifting operations need to do.
|x|
stands for the absolute value of x.
Comment:
You are right, the absolute value was forgotten. This should be valid for all a, b positive or negative