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.


numpy.binary_repr(num, width=None)

Version: 1.15.0


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

Returns: bin : str

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


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)



NumPy.binary_repr() method Example-2:

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



NumPy.binary_repr() method Example-3:

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



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)


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



Python - NumPy Code Editor:

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

Follow us on Facebook and Twitter for latest update.

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook