看到这样一个问题:只用位运算实现比较两整数大小
自己尝试了一下,写了个强行加入位运算的,但是有四则运算:
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
以上。