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.

user10869858
  • 481
  • 1
  • 3
  • 16
  • 1
    there are a lot of duplicates: [bitwise operators for finding less than](https://stackoverflow.com/q/14588160/995714), [Implement greater equal sign in C using only bitwise operations](https://stackoverflow.com/q/13396770/995714), [Bitwise operations equivalent of greater than operator](https://stackoverflow.com/q/10096599/995714), [Bitwise operation in C to compare two integers](https://stackoverflow.com/q/46136104/995714), [Replacing "==" with bitwise operators](https://stackoverflow.com/q/4161656/995714), [Compare two integers using bit operator](https://stackoverflow.com/q/31678344/995714) – phuclv Mar 06 '19 at 01:59
  • Basically you are computing the difference of a and b then checking for the sign of the difference – Juan Carlos Ramirez Mar 06 '19 at 02:28

0 Answers0