using xor for signedness

🏠

When multiplying or diving 2 numbers, determining the signedness of the result is not straightforward:

1a = -1
2b = 2
3sign = 1 if a * b > 0 else -1

Here we are actually going ahead and performing the multiplication. If we do not want to do so, then things get even more complicated:

 1a = -1
 2b = 2
 3sign = 1
 4if a > 0 and b > 0:
 5 sign = 1
 6elif a < 0 and b < 0:
 7 sign = 1
 8elif a > 0 and b < 0:
 9 sign = -1
10elif a < 0 and b > 0:
11 sign = -1

However you may notice that signedness of two numbers follows the same rules as xoring two bits, therefore the most efficient and simplest method is:

1a = -1
2b = 2
3sign = -1 if (a < 0) ^ (b < 0) else 1