reference:
http://www.geeksforgeeks.org/compute-the-integer-absolute-value-abs-without-branching/
Problem Definition:
Compute the integer absolute value (abs) without branching.
Solution:
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 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).
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
Code:
/* 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);
}
本文介绍了一种不使用条件分支来计算整数绝对值的方法。通过位操作实现负数的二进制补码翻转加一得到其绝对值,正数保持不变。具体步骤包括设置掩码、加掩码并进行异或运算。
8万+

被折叠的 条评论
为什么被折叠?



