仅使用按位运算在C中实现更大的等号 [英] Implement greater equal sign in C using only bitwise operations
本文介绍了仅使用按位运算在C中实现更大的等号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道许多基本操作(如加法或除法)也可以仅使用按位运算符在C中实现.如何使用大于或等于(> =)的符号进行相同操作?
I know that many basic operations like addition or division can also be implemented in C using only bitwise operators. How can I do the same with the greater than or equal sign (>=)?
if (x >= 0) {
...
}
推荐答案
我能想到的最简单的解决方案:
Simplest solution I can come up with:
#include <limits.h>
if ((x & INT_MAX) == x) // if (x >= 0)
...
如果您不喜欢==
,请使用XOR进行均等测试:
If you don't like the ==
then use XOR to do the equals test:
#include <limits.h>
if ((x & INT_MAX) ^ x) // if (x < 0)
...
else // else x >= 0
...
这篇关于仅使用按位运算在C中实现更大的等号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文