We will go over three tricks—checking whether the signs of integers are different, checking whether a number is a power of 2, and calculating the modulus of a number that is a power of 2. We will show an operators only notation and one using the corresponding NumPy functions:
Checking signs: The first trick depends on the
XOR
or^
operator. TheXOR
operator is also called the inequality operator; so, if the sign bit of the two operands is different, the XOR operation will lead to a negative number.^
corresponds to thebitwise_xor
function.<
corresponds to theless
function.x = numpy.arange(-9, 9) y = -x print "Sign different?", (x ^ y) < 0 print "Sign different?", numpy.less(numpy.bitwise_xor(x, y), 0)
The result is shown as follows:
Sign different? [ True True True True True True True True True False True True True True True True True True]Sign different? [ True True True True True True True True True False True True True...