views:

1846

answers:

16

Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?

A: 

if (x * y) > 0...

assuming non-zero and such.

Jekke
A: 

Just off the top of my head...

int mask = 1 << 31;
(a & mask) ^ (b & mask) < 0;
Daniel Spiewak
only works for 32 bit ints, which was not stipulated in the question
Larry Gritz
A: 

if (a*b < 0) sign is different, else sign is the same (or a or b is zero)

Doesn't work for overflow
Larry Gritz
+5  A: 

Assuming 32 bit ints:

bool same = ((x ^ y) & >> 31) != 1;

Slightly more terse:

bool same = !((x ^ y) & >> 31);
Patrick
Those two code examples should ALWAYS ALWAYS ALWAYS be preceded by a code comment please (in real life)
Jorge Córdoba
Oh, of course. In real life, I'd probably use something like same = Math.Sign(x) == Math.Sign(y). I just give evil bitwidily solutions when people ask for them. :D
Patrick
A: 

Thinking back to my university days, in most machine representations, isn't the left-most bit of a integer a 1 when the number is negative, and 0 when it's positive?

I imagine this is rather machine-dependent, though.

Dana
+2  A: 

(integer1 * integer2) > 0

Because when two integers share a sign, the result of multiplication will always be positive.

You can also make it >= 0 if you want to treat 0 as being the same sign no matter what.

toast
Only works until the product overflows.
Frosty
also, multiplication might be rather slow...
Daren Thomas
A: 

int same_sign = !( (x >> 31) ^ (y >> 31) );

if ( same_sign ) ... else ...

+2  A: 

As a technical note, bit-twiddly solutions are going to be much more efficient than multiplication, even on modern architectures. It's only about 3 cycles that you're saving, but you know what they say about a "penny saved"...

Daniel Spiewak
a penny saved is the root of all evil, say about 97% of the time?
ysth
+7  A: 

if ((a ^ b) >= 0) sign is the same

Oh, nice! :-) I'm surprised that I missed this one. The really nice thing about this solution is it doesn't depend upon a particular bit cardinality in the underlying integer representation.
Daniel Spiewak
+10  A: 

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.

SpoonMeiser
Also, those tricks decrease readability.
hop
The C Standard Lib provides a signbit() function. Probably tough to beat the optimiser with any "bitwise tricks" of your own devising.
hop
+13  A: 

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.

Torlack
Quite nice, the C/C++ hacker in me fully supports this code snippet. The software engineer in me questions why the user needs to know this in such a generic manner!
sixlettervariables
+1  A: 

For any size of int with two's complement arithmetic:

#define SIGNBIT (~((unsigned int)-1 >> 1))
if ((x & SIGNBIT) == (y & SIGNBIT))
    // signs are the same
Mark Ransom
A: 

assuming 32 bit

if ( ((x^y) & 0x80000000) == 0)

... the answer if(x*y>0) is bad due to overflow

ugasoft
A: 

I'm not really sure I'd consider "bitwise trick" and "simplest" to be synonymous. I see a lot of answers that are assuming signed 32-bit integers (though it would be silly to ask for unsigned); I'm not certain they'd apply to floating-point values.

It seems like the "simplest" check would be to compare how both values compare to 0; this is pretty generic assuming the types can be compared:

bool compare(T left, T right)
{
    return (left < 0) && (right < 0);
}

If the signs are opposite, you get false. If the signs are the same, you get true. If both items are 0, you get true and you can have fun figuring out what sign you want to attribute to that.

OwenP
Daniel Spiewak
+24  A: 

What's wrong with

return ((x<0) ==(y<0));

?

Rik
Um... Nothing...Sad that we all missed the simple solution.
Torlack
Great answer, simplicity is wonderful.
Aequitarum Custos
+2  A: 

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.