How to compute the integer absolute value

Same as existing answers, but with more explanations:

Let's assume a twos-complement number (as it's the usual case and you don't say otherwise) and let's assume 32-bit:

First, we perform an arithmetic right-shift by 31 bits. This shifts in all 1s for a negative number or all 0s for a positive one (but note that the actual >>-operator's behaviour in C or C++ is implementation defined for negative numbers, but will usually also perform an arithmetic shift, but let's just assume pseudocode or actual hardware instructions, since it sounds like homework anyway):

mask = x >> 31;

So what we get is 111...111 (-1) for negative numbers and 000...000 (0) for positives

Now we XOR this with x, getting the behaviour of a NOT for mask=111...111 (negative) and a no-op for mask=000...000 (positive):

x = x XOR mask;

And finally subtract our mask, which means +1 for negatives and +0/no-op for positives:

x = x - mask;

So for positives we perform an XOR with 0 and a subtraction of 0 and thus get the same number. And for negatives, we got (NOT x) + 1, which is exactly -x when using twos-complement representation.


Assume int is of 32-bit.

int my_abs(int x)
{
    int y = (x >> 31);
    return (x ^ y) - y;
}

  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 
    

One can also perform the above operation as:

return n*(((n>0)<<1)-1);

where n is the number whose absolute need to be calculated.