How to compute the integer absolute value

algorithm, bit-manipulation

Solution

Set the mask as right shift of integer by 31 (assuming integers are stored as two's-complement 32-bit values and that the right-shift operator does sign extension).

mask = n>>31 

XOR the mask with number

mask ^ n 

Subtract mask from result of step 2 and return the result.

(mask^n) - mask 

Problem

How to compute the integer absolute value without using `if` condition. I guess we need to use some bitwise operation. Can anybody help?

Original source

Related problems