Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?
if (x * y) > 0...
assuming non-zero and such.
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"...
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
Better way using std::signbit as follows:
std::signbit(firstNumber) == std::signbit(secondNumber);
It also support other basic types (double
, float
, char
etc).
Just off the top of my head...
int mask = 1 << 31;
(a & mask) ^ (b & mask) < 0;
if (a*b < 0) sign is different, else sign is the same (or a or b is zero)