unpackbits() function of numpy

The unpackbits() function creates an ndarray of binary bits from an ndarray of uint8. The Python example unpacks using the axis values both 0 and 1.

Bitwise Operations Updated 5 Oct 2024 1 min read

Overview

  • The numpy.unpackbits() unpacks an ndarray of numpy.uint8 integers into an ndarray of zeros and ones.
  • Note that the data type of the ndarray is not numpy.bool. It remains as numpy.uint8.
  • The numpy.unpackbits() does the reverse of numpy.packbits().

unpackbits() function of numpy

Example 1

python
# Example Python program that unpacks an ndarray of numpy.uint8 instances

            # into an ndarray of bits

            import numpy

# Create an ndarray. Elements are of type numpy.uint8

            intArray = numpy.ndarray(shape = (2, 2),

                                       dtype = numpy.uint8)

# Fill the ndarray with values

            intArray[0][0] = 10

            intArray[0][1] = 15

            intArray[1][0] = 20

            intArray[1][1] = 25

# Get the binary bits of the integer as an ndarray

            bitArray = numpy.unpackbits(intArray, axis = 1)

            print("Input array:")

            print(intArray)

print("Bit array when axis=1:")

            print(bitArray)

            print(bitArray.dtype)

            bitArray = numpy.unpackbits(intArray, axis = 0)

            print("Bit array when axis=0:")

            print(bitArray)

Output

Output
Input array:

[[10 15]

 [20 25]]

Bit array when axis=1:

[[0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 1]

 [0 0 0 1 0 1 0 0 0 0 0 1 1 0 0 1]]

uint8

Bit array when axis=0:

[[0 0]

 [0 0]

 [0 0]

 [0 0]

 [1 1]

 [0 1]

 [1 1]

 [0 1]

 [0 0]

 [0 0]

 [0 0]

 [1 1]

 [0 1]

 [1 0]

 [0 0]

 [0 1]]

Example 2

python
# Example Python program that unpacks an ndarray

            # of numpy.uint8 types in little endian bit order

            import numpy

intVals = numpy.ndarray(shape = (2, 2),

                                     dtype = numpy.uint8)

            intVals[0][0] = 1

            intVals[0][1] = 120

            intVals[1][0] = 128

            intVals[1][1] = 255

unpacked = numpy.unpackbits(intVals, bitorder = 'little')

            print("An ndarray of numpy.uint8 elements:")

            print(intVals)

            print("Unpacked ndarray - least significant bits are placed first:")

            print(unpacked)

Output

Output
An ndarray of numpy.uint8 elements:

[[  1 120]

 [128 255]]

Unpacked ndarray - least significant bits are placed first:

[1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]