Compute the integer absolute value (abs) without branching

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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值