Bitwise operations equivalent of greater than operator

后端 未结 8 1611
花落未央
花落未央 2020-12-05 10:30

I am working on a function that will essentially see which of two ints is larger. The parameters that are passed are 2 32-bit ints. The trick is the only operat

8条回答
  •  执念已碎
    2020-12-05 11:07

    A fully branchless version of Kaganar's smaller isGt function might look like so:

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

    This clocks in at around 60 instructions for the actual computation (MSVC 2010 compiler, on an x86 arch), plus an extra 10 stack ops or so for the function's prolog/epilog.

提交回复
热议问题