Time for action – twiddling bits
We will go over three tricks—checking whether the signs of integers are different, checking whether a number is a power of two, and calculating the modulus of a number that is a power of two. We will show an operators-only notation and one using the corresponding NumPy functions:
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 = np.arange(-9, 9) y = -x print "Sign different?", (x ^ y) < 0 print "Sign different?", np.less(np.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 True True True...