Compute the integer absolute value (abs) without branching

From WikiCoder
 int v;           // we want to find the absolute value of v
 unsigned int r;  // the result goes here 
 int const mask = v >> sizeof(int) * CHAR_BIT - 1;
 r = (v + mask) ^ mask;

Patented variation:

 r = (v ^ mask) - mask;

Some CPUs don't have an integer absolute value instruction (or the compiler fails to use them). On machines where branching is expensive, the above expression can be faster than the obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is the same.