Time for action – twiddling bits
We will now cover 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:
- 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, theXOR
operation will lead to a negative number (see https://www.khanacademy.org/computing/computer-science/cryptography/ciphers/a/xor-bitwise-operation).The following truth table illustrates the
XOR
operator:Input 1
Input 2
XOR
True
True
False
False
True
True
True
False
True
False
False
False
The
^
operator corresponds to thebitwise_xor()
function, and the<
operator corresponds to theless()
function:x = np.arange(-9, 9) y = -x print("Sign different?", (x ^ y) < 0) print("...