We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 2′s complement form, to get the absolute value of a negative number we have to toggle bits of the number and add 1 to the result.
Read full article from Compute the integer absolute value (abs) without branching | GeeksforGeeks
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add the mask to the given number.
mask + n
3) XOR of mask +n and mask gives the absolute value.
(mask + n)^mask
-X=~x+1 ==> -(X-1)=~(x-1)+1 => -X=~(X-1)
unsigned
int
getAbs(
int
n)
{
int
const
mask = n >> (
sizeof
(
int
) * CHAR_BIT - 1);//>>31
return
((n + mask) ^ mask);
}
Alternative Solution Subtract mask from result of step 2 and return the result.
(mask^n) - mask
unsigned int getAbs( int n) { int const mask = n >> ( sizeof ( int ) * CHAR_BIT - 1); return ((n ^ mask) - mask); } |