只用位运算实现比较两整数大小

2 篇文章 0 订阅

看到这样一个问题:只用位运算实现比较两整数大小
自己尝试了一下,写了个强行加入位运算的,但是有四则运算:

int i = 0xffffffff;
return (!((unsigned)(a-b)>>(sizeof(int)*8-1))*i)&a|(!((unsigned)(b-a)>>(sizeof(int)*8-1))*i)&b;

直接pass,;(

发现知乎上有这个解答:
https://www.zhihu.com/question/44356016

仰望高端玩家233333333,还是要吸收消化一下。

以下代码属于转载,特此申明,;)

作者:夏洋
链接:
https://www.zhihu.com/question/44356016/answer/97251524
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

int compare(uint32_t a, uint32_t b) {
  uint32_t diff = a ^ b;
  if (!diff) return 0;

    // 001xxxxx -> 00100000
    diff |= diff >> 1;
    diff |= diff >> 2;
    diff |= diff >> 4;
    diff |= diff >> 8;
    diff |= diff >> 16;
    diff ^= diff >> 1;
    return a & diff ? 1 : -1;
}

理解:
1.a==b 异或则为0
2.a < b 从高位向低位数起,二者第一次出现不同的二进制位时,a在该位处的值一定为0,b在该位处的值一定为1,反之亦然。

diff = a ^ b ,找diff中为1的那一位,a | 0 不变,a | 1 置1 ,那么>>16之后,为1的那一位还是1,为1之后的所有位都被置1

    diff |= diff >> 1;
    diff |= diff >> 2;
    diff |= diff >> 4;
    diff |= diff >> 8;
    diff |= diff >> 16;

为1的那一位置1,其他所有位因为异或,置0

    diff ^= diff >> 1;

检验a在该位是0还是1,是0的话说明a小,是1的话说明a大

    a & diff

以上。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值