Implement greater equal sign in C using only bitwise operations

半城伤御伤魂 提交于 2019-12-01 11:41:46

问题


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) {
    ...
}

回答1:


Simplest solution I can come up with:

#include <limits.h>

if ((x & INT_MAX) == x)    // if (x >= 0)
    ...

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
    ...



回答2:


If you only want if (x >= 0) then this is enough

if (~x & INT_MIN)

If you mean "greater than or equal" between 2 numbers in general then it's a lot more difference




回答3:


If all you can use is bitwise operators and even the comparison operators are disabled, it's not possible (actually, almost nothing would be possible). Implicit comparison is always present, even operations such as if(x some bitwise stuff) are actually interpreted as an equivalent to if(x some bitwise stuff) != 0) in the generated assembly code.



来源:https://stackoverflow.com/questions/13396770/implement-greater-equal-sign-in-c-using-only-bitwise-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!