bhupixb

Min_max

Jun 21st, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. Compute the minimum (min) or maximum (max) of two integers without branching
  2. int x; // we want to find the minimum of x and y
  3. int y;
  4. int r; // the result goes here
  5.  
  6. r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
  7. On some rare machines where branching is very expensive and no condition move instructions exist, the above expression might be faster than the obvious approach, r = (x < y) ? x : y, even though it involves two more instructions. (Typically, the obvious approach is best, though.) 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.
  8. To find the maximum, use:
  9.  
  10. r = x ^ ((x ^ y) & -(x < y)); // max(x, y)
Add Comment
Please, Sign In to add comment