The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit as 1 if they have opposite sign. In other words, XOR of x and y will be negative number if x and y have opposite signs. The following code use this logic.
Statement 1: Product of two integers with the same sign is always a positive integer.
What's wrong with
return ((x<0) == (y<0));
?
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 <typename valueType>
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.
(a ^ b) >= 0
will evaluate to 1 if the sign is the same, 0 otherwise.
I would be wary of any bitwise tricks to determine the sign of integers, as then you have to make assumptions about how those numbers are represented internally.
Almost 100% of the time, integers will be stored as two's compliment, but it's not good practice to make assumptions about the internals of a system unless you are using a datatype that guarentees a particular storage format.
In two's compliment, you can just check the last (left-most) bit in the integer to determine if it is negative, so you can compare just these two bits. This would mean that 0 would have the same sign as a positive number though, which is at odds with the sign function implemented in most languages.
Personally, I'd just use the sign function of your chosen language. It is unlikely that there would be any performance issues with a calculation such as this.
Assuming 32 bit ints:
bool same = ((x ^ y) >> 31) != 1;
Slightly more terse:
bool same = !((x ^ y) >> 31);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With