Simplest way to check if two integers have same sign?

前端 未结 18 2503
礼貌的吻别
礼貌的吻别 2020-12-04 13:53

Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?

相关标签:
18条回答
  • 2020-12-04 14:28

    if (x * y) > 0...

    assuming non-zero and such.

    0 讨论(0)
  • 2020-12-04 14:30

    As a technical note, bit-twiddly solutions are going to be much more efficient than multiplication, even on modern architectures. It's only about 3 cycles that you're saving, but you know what they say about a "penny saved"...

    0 讨论(0)
  • 2020-12-04 14:31

    For any size of int with two's complement arithmetic:

    #define SIGNBIT (~((unsigned int)-1 >> 1))
    if ((x & SIGNBIT) == (y & SIGNBIT))
        // signs are the same
    
    0 讨论(0)
  • 2020-12-04 14:34

    Better way using std::signbit as follows:

    std::signbit(firstNumber) == std::signbit(secondNumber);
    

    It also support other basic types (double, float, char etc).

    0 讨论(0)
  • 2020-12-04 14:39

    Just off the top of my head...

    int mask = 1 << 31;
    (a & mask) ^ (b & mask) < 0;
    
    0 讨论(0)
  • 2020-12-04 14:39

    if (a*b < 0) sign is different, else sign is the same (or a or b is zero)

    0 讨论(0)
提交回复
热议问题