Binary_repr() function of numpy

Overview:

  • The NumPy function binary_repr() returns a string of binary bits(i.e., ones and zeros) for a given number. The number could be any NumPy scalar of integer type or Boolean Type.

  • For negative integers the function returns the string of binary bits in twos complement form.

  • Unlike the other functions of NumPy, that perform bit-wise operations the binary_repr() function does not operate on one or more numpy array-likes or with a combination of array-like and scalar. It takes one numpy scalar and returns the corresponding binary string.

  • For a given integer the built-in function bin() also returns a string of binary bits. However, the output of the built-in function bin() does not accept bit-width as a parameter like the Numpy binary_repr() does. Because of this, there is no need for the bin() function to use zfill() and prefix the results with zeros.

Example:

# Example Python program that converts the 
# given numpy scalars(integer and Boolean) 
# to binary strings.
import sys
import numpy

# Start with True
num         = True #CPython type
binaryForm     = numpy.binary_repr(num, 8)
print("Boolean value: True")
print(binaryForm)

num         = numpy.bool(True) #NumPy type
binaryForm     = numpy.binary_repr(num, 8)
print(binaryForm)

# Maximum integer value
num         = sys.maxsize #CPython type
binaryForm     = numpy.binary_repr(num, 64)
print("Integer value in decimal form:%d"%num)
print("Integer value in binary form:")
print(binaryForm)

# Negative value
num = numpy.byte(-5)
binaryForm     = numpy.binary_repr(num, 8)
print("Negative integer value:%d"%num)
print("Negative value in binary form:")
print(binaryForm)
print(type(binaryForm))

Output:

Boolean value: True

00000001

00000001

Integer value in decimal form:9223372036854775807

Integer value in binary form:

0111111111111111111111111111111111111111111111111111111111111111

Negative integer value:-5

Negative value in binary form:

11111011

<class 'str'>

 


Copyright 2024 © pythontic.com