Topics / Bit Manipulation / Q14
How do you check if two integers have opposite signs?
Short answer: (a ^ b) < 0. XOR of two numbers has its sign bit set only when the two sign bits differ, so the result is negative exactly when the signs are opposite.
#include <stdbool.h>
bool opposite_signs(int a, int b)
{
return (a ^ b) < 0;
}
Example
a = 5 -> 0000...0101
b = -3 -> 1111...1101
a ^ b -> 1111...1000 (sign bit 1, negative) -> opposite signs
a = -5, b = -3 -> sign bits both 1 -> XOR sign bit 0 -> same sign
Edge cases
- Zero counts as positive, so
opposite_signs(0, -1)is true andopposite_signs(0, 5)is false. Say this out loud in an interview. - No overflow is possible: XOR never overflows, unlike
a * b < 0, which can overflow for large values (undefined behaviour for signed types).
Readable alternative: (a < 0) != (b < 0). Modern compilers generate the same code, so this is preferable in production.
Where it is used: detecting a zero crossing in a signal (consecutive samples with opposite signs), and overflow checks: for s = a + b, overflow happened if a and b have the same sign and s has a different sign: ((a ^ s) & (b ^ s)) < 0. Compute s with unsigned arithmetic so the addition itself is not undefined.