w3resource

NumPy Input and Output: binary_repr() function

numpy.binary_repr() function

The binary_repr() function is used to get the binary representation of the input number as a string.

For negative numbers, if width is not given, a minus sign is added to the front.
If width is given, the two’s complement of the number is returned, with respect to that width.

In a two's-complement system negative numbers are represented by the two's complement of the absolute value.
This is the most common method of representing signed integers on computers [R16].
A N-bit two's-complement system can represent every integer in the range -2^{N-1} to +2^{N-1}-1.

Syntax:

numpy.binary_repr(num, width=None)

Version: 1.15.0

Parameter:

Name Description Required /
Optional
num Only an integer decimal number can be used.
int
Required

Returns: bin : str

Binary representation of num or two's complement of num.

Notes:

binary_repr is equivalent to using base_repr with base 2, but about 25x faster.

NumPy.binary_repr() method Example-1:

>>> import numpy as np
>>> np.binary_repr(5)

Output:

'101'

NumPy.binary_repr() method Example-2:

>>> import numpy as np
>>> np.binary_repr(-5)

Output:

'-101'

NumPy.binary_repr() method Example-3:

>>> import numpy as np
>>> np.binary_repr(5, width=4)

Output:

'0101'

The two's complement is returned when the input number is negative and width is specified:

>>> import numpy as np
>>> np.binary_repr(-2, width=3)

Output:

'110'
>>> import numpy as np
>>> np.binary_repr(-2, width=5)

Output:

'11110'

Python - NumPy Code Editor:

Previous: printoptions() function
Next: base_repr() function



Follow us on Facebook and Twitter for latest update.