仅使用按位运算来实现>,> =,<,<=

时间:2019-03-06 00:32:35

标签: bit-manipulation comparison-operators

我看过thisthis,从中至少可以得到>的形式:

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;
}

我想知道>=<<=的等效物是什么,并且通常简短地说明其工作方式/原因。我试图自己弄清楚它们,但是一开始很难理解这个isGt的工作原理。

0 个答案:

没有答案