Simplest way to check if two integers have same sign?

前端 未结 18 2549
礼貌的吻别
礼貌的吻别 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);
    

提交回复
热议问题