[ Web Proxy ]
URL:
Viewing: https://numpy.org/doc/stable/reference/generated/numpy.binary_repr.html [Back]  [Original]

numpy.binary_repr — NumPy v2.5 Manual
Back to top
Search the docs ...:

numpy.binary_repr#

numpy.binary_repr(num, width=None)[source]#

Return 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 twos complement of the number is returned, with respect to that width.

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

Parameters:
numint

Only an integer decimal number can be used.

widthint, optional

The length of the returned string if num is positive, or the length of the twos complement if num is negative, provided that width is at least a sufficient number of bits for num to be represented in the designated form. If the width value is insufficient, an error is raised.

Returns:
binstr

Binary representation of num or twos complement of num.

See also

base_repr

Return a string representation of a number in the given base system.

bin

Pythons built-in binary representation generator of an integer.

Notes

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

References

[1]

Wikipedia, Twos complement, https://en.wikipedia.org/wiki/Twos_complement

Examples

Try it in your browser!
>>> import numpy as np
>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'

The twos complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'

Web Proxy Viewer  |  New URL  |  Original Page