How >, >=, <, <= are implemented using only bitwise operations

3

I have seen this and this, from which at least the > is obtained as:

int isGt(int a, int b)
{
    int diff = a ^ b;
    diff |= diff >> 1;
    diff |= diff >> 2;
    diff |= diff >> 4;
    diff |= diff >> 8;
    diff |= diff >> 16;

    //1+ on GT, 0 otherwise.
    diff &= ~(diff >> 1) | 0x80000000;
    diff &= (a ^ 0x80000000) & (b ^ 0x7fffffff);

    //flatten back to range of 0 or 1.
    diff |= diff >> 1;
    diff |= diff >> 2;
    diff |= diff >> 4;
    diff |= diff >> 8;
    diff |= diff >> 16;
    diff &= 1;

    return diff;
}

I am wondering what the equivalent for >=, <, and <= are, and generally a short description of how/why it works. I am trying to figure them out on my own but am having difficulty understanding how this isGt works in the first place.

bit-manipulation
comparison-operators
asked on Stack Overflow Mar 6, 2019 by user10869858

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0