w3resource

NumPy: Convert a given vector of integers to a matrix of binary representation


Convert integer vector to binary matrix.

Write a NumPy program to convert a given vector of integers to a matrix of binary representation.

Pictorial Presentation:

Python NumPy: Convert a given vector of integers to a matrix of binary representation

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array 'nums' containing a set of integers
nums = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15])

# Displaying the original vector 'nums'
print("Original vector:")
print(nums)

# Creating a binary representation of 'nums' using bitwise operations and reshaping
# The resultant array represents the binary representation of each element in 'nums'
bin_nums = ((nums.reshape(-1, 1) & (2 ** np.arange(8))) != 0).astype(int)

# Displaying the binary representation of the vector 'nums'
print("\nBinary representation of the said vector:")
print(bin_nums[:, ::-1])  # Reversing the columns to display binary digits in the correct order

Sample Output:

Original vector:
[ 0  1  3  5  7  9 11 13 15]

Binary representation of the said vector:
[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 1 1]
 [0 0 0 0 0 1 0 1]
 [0 0 0 0 0 1 1 1]
 [0 0 0 0 1 0 0 1]
 [0 0 0 0 1 0 1 1]
 [0 0 0 0 1 1 0 1]
 [0 0 0 0 1 1 1 1]]

Explanation:

In the above exercise -

nums = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15]): Creates a Numpy array with specified values.

bin_nums = ((nums.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)

In the above code -

  • nums.reshape(-1,1): Reshapes nums into a 2D column array of shape (9, 1).
  • 2**np.arange(8): Creates an array of powers of 2 from 2^0 to 2^7.
  • nums.reshape(-1,1) & (2**np.arange(8)): Applies the bitwise AND operation between the reshaped nums array and the powers of 2 array using broadcasting. This operation is a way to extract the binary digits for each number in nums.
  • ((nums.reshape(-1,1) & (2**np.arange(8))) != 0): Compares the result of the bitwise AND operation with 0. If the result is not equal to 0, it returns True; otherwise, it returns False.
  • ((nums.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int): Converts the boolean array obtained in the previous step into an integer array, where True becomes 1 and False becomes 0. This array represents the binary representation of the numbers in nums, but the order of the bits is reversed.

bin_nums[:,::-1]: Reverses the order of the bits in each row of the bin_nums array to obtain the correct binary representation.

print(bin_nums[:,::-1]): Prints the resulting array containing the binary representations of the numbers in “nums” with 8 bits.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to convert a vector of integers into their binary representations as rows of a matrix using np.binary_repr.
  • Create a function that maps each integer in an array to an 8-bit binary vector and stacks the results.
  • Implement a solution that uses vectorized operations to convert a 1D array of integers to a 2D binary array.
  • Test the conversion on a range of integers and verify that each row in the binary matrix has consistent width.

Go to:


PREV : Multiply arrays of compatible dimensions.
NEXT : Extract rows with unequal values.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.