Simplest way to check if two integers have same sign?

前端 未结 18 2504
礼貌的吻别
礼貌的吻别 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:46

    Assuming 32 bit ints:

    bool same = ((x ^ y) >> 31) != 1;
    

    Slightly more terse:

    bool same = !((x ^ y) >> 31);
    
    0 讨论(0)
  • 2020-12-04 14:48

    Thinking back to my university days, in most machine representations, isn't the left-most bit of a integer a 1 when the number is negative, and 0 when it's positive?

    I imagine this is rather machine-dependent, though.

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

    assuming 32 bit

    if(((x^y) & 0x80000000) == 0)

    ... the answer if(x*y>0) is bad due to overflow

    0 讨论(0)
  • 2020-12-04 14:52
    (a ^ b) >= 0
    

    will evaluate to 1 if the sign is the same, 0 otherwise.

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

    int same_sign = !( (x >> 31) ^ (y >> 31) );

    if ( same_sign ) ... else ...

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

    What's wrong with

    return ((x<0) == (y<0));  
    

    ?

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