Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?
Here is a version that works in C/C++ that doesn't rely on integer sizes or have the overflow problem (i.e. x*y>=0 doesn't work)
bool SameSign(int x, int y)
{
return (x >= 0) ^ (y < 0);
}
Of course, you can geek out and template:
template
bool SameSign(typename valueType x, typename valueType y)
{
return (x >= 0) ^ (y < 0);
}
Note: Since we are using exclusive or, we want the LHS and the RHS to be different when the signs are the same, thus the different check against zero.