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.

For example -2 in a 8 bit system is stored as follows 1 1 1 1 1 1 1 0 where leftmost bit is the sign bit. To get the absolute value of a negative number, we have to toggle all bits and add 1 to the toggled number i.e, 0 0 0 0 0 0 0 1 + 1 will give the absolute value of 1 1 1 1 1 1 1 0. Also remember, we need to do these operations only if the number is negative (sign bit is set).

Method 1
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).

mask = n>>31

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

Implementation:

[pastacode lang=”c” manual=”%23include%20%3Cstdio.h%3E%0A%23define%20CHAR_BIT%208%0A%20%0A%2F*%20This%20function%20will%20return%20absoulte%20value%20of%20n*%2F%0Aunsigned%20int%20getAbs(int%20n)%0A%7B%0A%20%20int%20const%20mask%20%3D%20n%20%3E%3E%20(sizeof(int)%20*%20CHAR_BIT%20-%201)%3B%0A%20%20return%20((n%20%2B%20mask)%20%5E%20mask)%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20function%20*%2F%0Aint%20main()%0A%7B%0A%20%20int%20n%20%3D%20-6%3B%0A%20%20printf(%22Absoute%20value%20of%20%25d%20is%20%25u%22%2C%20n%2C%20getAbs(n))%3B%0A%20%0A%20%20getchar()%3B%0A%20%20return%200%3B%0A%7D%0ARun%20on%20IDE%0A” message=”c” highlight=”” provider=”manual”/] [ad type=”banner”]

Method 2:
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).

 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

Implementation:

 

[pastacode lang=”c” manual=”%2F*%20This%20function%20will%20return%20absoulte%20value%20of%20n*%2F%0Aunsigned%20int%20getAbs(int%20n)%0A%7B%0A%20%20int%20const%20mask%20%3D%20n%20%3E%3E%20(sizeof(int)%20*%20CHAR_BIT%20-%201)%3B%0A%20%20return%20((n%20%5E%20mask)%20-%20mask)%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]

On machines where branching is expensive, the above expression can be faster than the obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is the same.

[ad type=”banner”]

 

Categorized in: