Checking whether a number is positive or negative using bitwise operators

后端 未结 16 941
轮回少年
轮回少年 2020-12-08 20:01

I can check whether a number is odd/even using bitwise operators. Can I check whether a number is positive/zero/negative without using any conditional statements/operators l

16条回答
  •  攒了一身酷
    2020-12-08 20:37

    Here is an update related to C++11 for this old question. It is also worth considering std::signbit.

    On Compiler Explorer using gcc 7.3 64bit with -O3 optimization, this code

    bool s1(double d)
    {
        return d < 0.0;
    }
    

    generates

    s1(double):
      pxor xmm1, xmm1
      ucomisd xmm1, xmm0
      seta al
      ret
    

    And this code

    bool s2(double d)
    {
        return std::signbit(d);
    }
    

    generates

    s2(double):
      movmskpd eax, xmm0
      and eax, 1
      ret
    

    You would need to profile to ensure that there is any speed difference, but the signbit version does use 1 less opcode.

提交回复
热议问题