algorithmbit-manipulation

How to compute the integer absolute value


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


Solution

    1. 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 
      
    2. XOR the mask with number

      mask ^ n 
      
    3. Subtract mask from result of step 2 and return the result.

      (mask^n) - mask