Assuming x is a 32-bit integer with the sign in the 32th (leftmost) bit,
int mask = x >> 31;
"mask" holds now either -1 (if x was negative) or 0. If it is -1, its binary representation is 0xffffffff (all 1's).
return (x ^ mask)
So x^mask is x XORed with either all 0s (remaining unchanged) or all 1's, including sign, which will invert its sign and map it to the positive value one less than the original. So 42 will remain 42, but -42 will become 41.
+ ~mask
not-mask will be 0 if x is negative, or all 1's, i.e. 0xffffffff (hence -1) if x was positive. Adding it, 42 will yield 41, and -42 (which was transformed to 41) will remain 41. Note that now in both cases we have the same number.
+ 1L;
Now, 42 (which was changed to 41) will become back 42, while -42 (which was 41) will become 42. The L is superfluous, as 1 alone will be taken as an int.
All in all, the function will return a value if it's positive, its opposite (i.e. its absolute value) if not.
NOTE: this function will obviously fail if its argument is the minimum (maximally negative) number, as that number has no positive representation in the same space as integers. So, mystery(-2147483647)
will yield 2147483647 as expected, but mystery(-2147483648)
will yield -2147483648.
Chances are very good that you'll fare better by using abs()
instead of your mystery function, which could be an abs
implementation for some architectures, while abs
tends to be the best implementation for each architecture it's compiled for.