本文共 697 字,大约阅读时间需要 2 分钟。
The key idea is to incorporate the branch into one equation.
Minimum of x and y will be
y ^ ((x ^ y) & -(x < y))
It works because if x < y, then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x. Otherwise, if x >= y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y.On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.
To find the maximum, use
x ^ ((x ^ y) & -(x < y));
/*Function to find minimum of x and y*/int min(int x, int y){ return y ^ ((x ^ y) & -(x < y));} /*Function to find maximum of x and y*/int max(int x, int y){ return x ^ ((x ^ y) & -(x < y)); }
转载地址:http://xexti.baihongyu.com/