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 thefront. If width is given, the two’s complement of the number isreturned, with respect to that width.

In a two’s-complement system negative numbers are represented by the two’scomplement of the absolute value. This is the most common method ofrepresenting signed integers on computers[1]. A N-bit two’s-complementsystem 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 ifnum is positive, or the lengthof the two’s complement ifnum is negative, provided thatwidth isat least a sufficient number of bits fornum to be represented inthe designated form. If thewidth value is insufficient, an error israised.

Returns:
binstr

Binary representation ofnum or two’s complement ofnum.

See also

base_repr

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

bin

Python’s built-in binary representation generator of an integer.

Notes

binary_repr is equivalent to usingbase_repr with base 2, but about 25xfaster.

References

[1]

Wikipedia, “Two’s complement”,https://en.wikipedia.org/wiki/Two’s_complement

Examples

>>>importnumpyasnp>>>np.binary_repr(3)'11'>>>np.binary_repr(-3)'-11'>>>np.binary_repr(3,width=4)'0011'

The two’s complement is returned when the input number is negative andwidth is specified:

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