Numpy binary_repr() Function



The NumPy binary_repr() function returns the binary representation of a given integer as a string. It converts a non-negative integer to its binary format with optionally padding the result with leading zeros to fit a specified width.

This function is useful for visualizing binary equivalents of integers, particularly in applications involving bitwise operations.

To this function if the width parameter is provided and is greater than the minimum required width then the output is padded with leading zeros. This function does not handle negative integers.

Syntax

Following is the syntax of Numpy binary_repr() function −

numpy.binary_repr(num, width=None)

Parameters

Following are the Parameters of Numpy binary_repr() function −

  • num(int): This is the input non-negative integer to be converted to binary representation.
  • width(int, optional): This is the length of the returned string that has to be padded with leading zeros if necessary. If width is not provided then the function returns the minimum number of bits required to represent the number.

Return value

This function returns binary representation of the integer as a string.

Example 1

Following is the basic example of Numpy binary_repr() function which converts the given integer 10 to its binary representation by resulting the representation as '1010' −

import numpy as np

# Convert an integer to binary without specifying width
binary_representation = np.binary_repr(10)
print("Binary representation of 10:", binary_representation)  

Below is the output of binary_repr() function −

Binary representation of 10: 1010

Example 2

Here this is the example which converts the integer 10 to its binary representation and pads the result with leading zeros to fit a width of 8 −

import numpy as np

# Convert an integer to binary with a specified width
binary_representation_with_width = np.binary_repr(10, width=8)
print("Binary representation of 10 with width 8:", binary_representation_with_width)

Following is the output for the above example −

Binary representation of 10 with width 8: 00001010
numpy_binary_operators.htm
Advertisements