如何计算整数绝对值 [英] How to compute the integer absolute value
本文介绍了如何计算整数绝对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算整数绝对值如果没有条件使用。 我想我们需要使用一些位运算。 任何人都可以帮忙吗?
How to compute the integer absolute value without using if condition. I guess we need to use some bitwise operation. Can anybody help?
推荐答案
1)31设置屏蔽整数作为右移(假设整数存储为二进制补码32位值和右移操作者符号扩展)。
1) Set the mask as right shift of integer by 31 (assuming integers are stored as two's-complement 32-bit values and that the right-shift operator does sign extension).
mask = n>>31
2)XOR与数量面具
2) XOR the mask with number
mask ^ n
3)从步骤2的结果中减去面具,并返回结果。
3) Subtract mask from result of step 2 and return the result.
(mask^n) - mask
这篇关于如何计算整数绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文