Numpy ununpackbits() Function



The NumPy unpackbits() function is used to unpack elements of a uint8 array into a binary-valued output array. It converts each byte (8 bits) in the input array into its corresponding binary representation, resulting in an array of bits.

This function is useful for expanding packed binary data back into a bit-level representation. The unpacking process can be performed along a specified axis and the bit order can be set to 'big' by default or 'little' endian by determining whether the most or least significant bit comes first.

Syntax

Following is the syntax of Numpy unpackbits() function −

numpy.unpackbits(a, /, axis=None, count=None, bitorder='big')

Parameters

Following are the Parameters of Numpy unpackbits() function −

  • a(array_like): The input array of type uint8.
  • axis(int, optional): The axis along which to unpack the bits. If None then the input array is flattened before unpacking.
  • count(int or None, optional): The number of bits to unpack. Must be a multiple of 8. If None then all bits are unpacked.
  • bitorder({'big', 'little'}, optional): The order of the bits in the packed representation. The Parameter 'big' means the most significant bit is first while 'little' means the least significant bit is first. The default value is 'big'.

Return value

This function returns an array where each element is unpacked into its constituent bits. The returned array has a dtype of uint8.

Example 1

Following is the basic example of Numpy unpackbits() function in which converting the packed binary data i.e. bytes into an array of bits that can be useful for bit-level operations or analysis −

import numpy as np

# Define a 1D array of uint8 values (bytes)
byte_array = np.array([0b10101010, 0b11001100], dtype=np.uint8)

# Unpack the bytes into individual bits
unpacked_array = np.unpackbits(byte_array)

print("Original byte array:", byte_array)
print("Unpacked array of bits:", unpacked_array)  

Below is the output of unpackbits() function −

Original byte array: [170 204]
Unpacked array of bits: [1 0 1 0 1 0 1 0 1 1 0 0 1 1 0 0]

Example 2

We can unpack a 2D array of uint8 values into individual bits along the last axis using unpackbits(). Here is the example which shows the unpacking of the 2d array along the axis −

import numpy as np

# Define a 2D array of uint8 values (bytes)
byte_array_2d = np.array([[0b10101010, 0b11001100], [0b11110000, 0b00001111]], dtype=np.uint8)

# Unpack the bytes into individual bits along the last axis (axis=1)
unpacked_array = np.unpackbits(byte_array_2d, axis=1)

print("Original 2D byte array:")
print(byte_array_2d)
print("\nUnpacked array of bits along the last axis:")
print(unpacked_array)

Following is the output for the above example −

Original 2D byte array:
[[170 204]
 [240  15]]

Unpacked array of bits along the last axis:
[[1 0 1 0 1 0 1 0 1 1 0 0 1 1 0 0]
 [1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1]]
numpy_binary_operators.htm
Advertisements