Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 49 ยท Array Math

Bitwise Operations and Integer Functions

Use NumPy bitwise_and, bitwise_or, bitwise_xor, invert and shifts on integer arrays, build flag masks, and meet gcd, lcm, packbits and unpackbits with runnable examples.

Every integer in a computer is a row of bits, and NumPy lets you work on those bits for a whole array at once. This is useful far beyond low-level programming: permission flags, compact feature sets, hash mixing, checksums, bit-packed images and many puzzle problems become short vectorized expressions.

In this lesson you meet the bitwise ufuncs (&, |, ^, ~, <<, >>), build and test flag masks, compress boolean arrays with np.packbits, and use the integer helpers np.gcd and np.lcm. You should already be comfortable with boolean masks and with dtypes, because the width of the integer type decides what the bits mean.

The bitwise operators

Each operator is the symbol form of a ufunc, so it works elementwise on integer arrays and on boolean arrays.

Operator Ufunc Meaning
a & b np.bitwise_and 1 where both bits are 1
a | b np.bitwise_or 1 where at least one bit is 1
a ^ b np.bitwise_xor 1 where the bits differ
~a np.invert flips every bit
a << k np.left_shift moves bits left, multiplying by 2**k
a >> k np.right_shift moves bits right, dividing by 2**k (floor)

Use np.binary_repr(n, width) to see the bits of a single integer.

Python Bitwise operators on arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details trip people up. First, ~ on a signed integer gives -x - 1 because of two's complement, while on an unsigned integer it gives the complement within the type's width. Second, the result stays in the same dtype, so shifting a uint8 left can silently drop bits. Pick a wide enough dtype before you shift.

On boolean arrays, &, |, ^ and ~ mean logical and, or, xor and not, which is how boolean masks are combined. The words and, or and not do not work on arrays with more than one element.

Flag masks

A common use is to store several yes/no properties in one integer, one bit per property. You test a flag with &, set it with |, clear it with & ~flag, and toggle it with ^.

Python Permission flags in one integer column

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

np.bitwise_count (NumPy 2.0 and later) counts the 1 bits of each element, also called the population count or Hamming weight. Together with xor it gives the Hamming distance between two numbers: np.bitwise_count(a ^ b).

Bit tricks that vectorize well

A few classic one-liners work on whole arrays:

  • Even or odd: n & 1 is 1 for odd numbers.
  • Power of two: (n > 0) & ((n & (n - 1)) == 0).
  • Lowest set bit: n & -n for signed integers.
  • Pack small numbers: (hi << 4) | lo stores two 4-bit values in one byte.
Python Classic bit tricks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

gcd and lcm

np.gcd returns the greatest common divisor and np.lcm the least common multiple, elementwise and with broadcasting. They also have reduce methods, so you can fold a whole array into one number.

Python gcd, lcm and reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

packbits and unpackbits

A boolean array uses one byte per element. np.packbits squeezes eight booleans into a single uint8, an 8-fold saving, and np.unpackbits restores them. Bit order is big-endian by default (the first element becomes the most significant bit); pass bitorder="little" for the opposite. If the length is not a multiple of eight, the end is padded with zeros, so keep the original length around.

Python Compressing booleans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Packed bits are handy for storing large boolean grids such as a visited map or a binary image, and for hashing. Any computation still needs them unpacked, so pack when you store or send data, not while you calculate.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which expression clears the WRITE flag (value 2) from every element of the integer array perms?

    ~2 has every bit set except the WRITE bit, so and-ing with it keeps all other bits and clears that one. perms ^ 2 would toggle it instead of clearing it.
  2. 2. What does np.array([200], dtype=np.uint8) << 1 return?

    The result keeps the uint8 dtype, so the bit shifted out of the top is dropped. 400 modulo 256 is 144.
  3. 3. Which call gives the greatest common divisor of all numbers in an array nums?

    np.gcd takes two arguments. Its reduce method applies it pairwise along the array and returns one number.
  4. 4. np.packbits on 11 booleans returns how many bytes?

    Eight booleans fit in one byte, and the remaining three are padded with zeros in a second byte.

Summary

  • &, |, ^, ~, << and >> are ufuncs for integer arrays; on booleans they are logical operators.
  • The result keeps the input dtype, so unsigned values wrap and shifts can drop bits.
  • Test a flag with x & f, set with x | f, clear with x & ~f, toggle with x ^ f.
  • np.bitwise_count counts 1 bits and, combined with xor, gives the Hamming distance.
  • np.gcd and np.lcm work elementwise and fold with .reduce.
  • np.packbits and np.unpackbits convert between booleans and bytes; remember the padding.

Next: Comparing Arrays and Floating Point.