本文共 1587 字,大约阅读时间需要 5 分钟。
Compute the integer absolute value (abs) without branching.
There is also a very simple solution without using bit manipulation, i.e. (-2*(x<0)+1)*x.
We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 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).
If x is negtive, firstly we can flip each bit of abs(x), and finally add 1 to it get the
binary representation of x. so if we wanna get the binary representation of abs(x) in this case, we can first minus one to x, and then filp over for every bit.
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 (need more attention here) 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
/* This function will return absoulte value of n*/unsigned int getAbs(int n){ int const mask = n >> (sizeof(int) * CHAR_BIT - 1); return ((n + mask) ^ mask);}
转载地址:http://oexti.baihongyu.com/