博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Compute the integer absolute value (abs) without branching
阅读量:4151 次
发布时间:2019-05-25

本文共 1587 字,大约阅读时间需要 5 分钟。

reference: 

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

转载地址:http://oexti.baihongyu.com/

你可能感兴趣的文章
Doxygen + Graphviz windows下安装配置(图解)
查看>>
win8 PL2303驱动的问题
查看>>
vim中寄存器使用和vim标记
查看>>
原码、反码和补码
查看>>
STM32中断(转载)
查看>>
STM32 flash操作
查看>>
gedit assertion `lang != NULL' failed
查看>>
ubuntu10.10 教育网 使用ipv6,亲测可用【经过再次验证与修正】
查看>>
google搜索技巧
查看>>
锂电池相关
查看>>
用openjtag&eclipse测试mini2440流水灯程序
查看>>
ARM Linux启动分析----head-armv.S内幕
查看>>
链接脚本
查看>>
openjtag openocd libftd2xx
查看>>
ARM汇编伪指令
查看>>
字节序问题--大端法小端法
查看>>
STM32 USART
查看>>
Ubuntu中vim和gedit显示中文乱码
查看>>
解决Rhythmbox乱码
查看>>
豆瓣爱问共享资料插件发布啦
查看>>