Embed an equal sign in C using only bitwise operations

I know that many basic operations, such as addition or division, can also be implemented in C using only bitwise operators. How can I do the same with a greater or equal sign (> =)?

if (x >= 0) {
    ...
}
+1
source share
3 answers

The simplest solution I can come up with:

#include <limits.h>

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

If you don't like it ==, then use XOR to run the equals test:

#include <limits.h>

if ((x & INT_MAX) ^ x)    // if (x < 0)
    ...
else                      // else x >= 0
    ...
+1
source

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

if (~x & INT_MIN)

If you mean "more or equal" between the two numbers in general, then this is much more than the difference

0
source

If all you can use is bitwise operators, and even comparison operators are disabled, this is not possible (in fact, almost nothing would have been possible). Implicit comparison is always present, even operations, such as if(x some bitwise stuff), are actually interpreted as equivalent if(x some bitwise stuff) != 0)in the generated assembler code.

-1
source

Source: https://habr.com/ru/post/1696392/


All Articles