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 ...
Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.