Simplest way to check if two integers have same sign?

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

    Assuming twos complement arithmetic (http://en.wikipedia.org/wiki/Two_complement):

    inline bool same_sign(int x, int y) {
        return (x^y) >= 0;
    }
    

    This can take as little as two instructions and less than 1ns on a modern processor with optimization.

    Not assuming twos complement arithmetic:

    inline bool same_sign(int x, int y) {
        return (x<0) == (y<0);
    }
    

    This may require one or two extra instructions and take a little longer.

    Using multiplication is a bad idea because it is vulnerable to overflow.

提交回复
热议问题