# using xor for signedness

Go Back home

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

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


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

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

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