Simplest way to check if two integers have same sign?

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

    branchless C version:

    int sameSign(int a, int b) {
        return ~(a^b) & (1<<(sizeof(int)*8-1));
    }
    

    C++ template for integer types:

    template  T sameSign(T a, T b) {
        return ~(a^b) & (1<<(sizeof(T)*8-1));
    }
    

提交回复
热议问题