w3resource

NumPy Binary operations: unpackbits() function

numpy.unpackbits() function

The unpackbits() function is used to unpack elements of a uint8 array into a binary-valued output array.
Note: Each element of myarray represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.

Some common applications of numpy.unpackbits() include:
Data Decompression: Unpacking compressed binary data stored in byte arrays back into binary arrays for further processing or analysis.
Image Processing: Converting compact byte arrays of binary images or masks back into binary arrays for manipulation, display, or further processing.
Cryptography: Converting byte-level representations of encrypted data or keys back into bit-level representations for decryption or analysis.
Network Communication: Unpacking byte arrays of binary data or bit fields received over network protocols that require byte-aligned data, back into binary arrays for further processing or analysis.

Syntax:

numpy.unpackbits(myarray, axis=None)

Parameters:

Name Description Required /
Optional
myarray Input array Required
axis The dimension over which bit-unpacking is done. None implies unpacking the flattened array. Optional

Return value:
unpacked [ndarray, uint8 type]
The elements are binary-valued (0 or 1).

Example: Unpacking byte arrays into binary arrays with NumPy

>>> import numpy as np
>>> x = np.array([[3], [5], [15]], dtype=np.uint8)
>>> x
array([[ 3],
       [ 5],
       [15]], dtype=uint8)
>>> y = np.unpackbits(x, axis=1)
>>> y
array([[0, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 1, 0, 1],
       [0, 0, 0, 0, 1, 1, 1, 1]], dtype=uint8)

In the above code, a 2-dimensional NumPy array x with the shape (3, 1) and dtype uint8 is created. The numpy.unpackbits() function is used to unpack the byte values in x along the specified axis (axis=1) into binary arrays. The resulting y array has the shape (3, 8) and contains the unpacked binary representation of the input byte data.

Python Code Editor:

Previous: packbits()
Next: binary_repr()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/numpy/binary-operations/unpackbits.php