Skip to content

Commit cd8a9ff

Browse files
committed
Implement dpnp.binary_repr
1 parent 11f251d commit cd8a9ff

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

dpnp/dpnp_iface_bitwise.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,12 @@
4141

4242

4343
import dpctl.tensor._tensor_elementwise_impl as ti
44+
import numpy
4445

4546
from dpnp.dpnp_algo.dpnp_elementwise_common import DPNPBinaryFunc, DPNPUnaryFunc
4647

4748
__all__ = [
49+
"binary_repr",
4850
"bitwise_and",
4951
"bitwise_invert",
5052
"bitwise_left_shift",
@@ -58,6 +60,71 @@
5860
]
5961

6062

63+
def binary_repr(num, width=None):
64+
"""
65+
Return the binary representation of the input number as a string.
66+
67+
For negative numbers, if `width` is not given, a minus sign is added to the
68+
front. If `width` is given, the two's complement of the number is returned,
69+
with respect to that width.
70+
71+
In a two's-complement system negative numbers are represented by the two's
72+
complement of the absolute value. A N-bit two's-complement system can
73+
represent every integer in the range :math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
74+
75+
For full documentation refer to :obj:`numpy.binary_repr`.
76+
77+
Parameters
78+
----------
79+
num : int
80+
Only an integer decimal number can be used.
81+
width : {None, int}, optional
82+
The length of the returned string if `num` is positive, or the length
83+
of the two's complement if `num` is negative, provided that `width` is
84+
at least a sufficient number of bits for `num` to be represented in the
85+
designated form. If the `width` value is insufficient, an error is
86+
raised.
87+
Default: ``None``.
88+
89+
Returns
90+
-------
91+
bin : str
92+
Binary representation of `num` or two's complement of `num`.
93+
94+
See Also
95+
--------
96+
:obj:`dpnp.base_repr` : Return a string representation of a number in the
97+
given base system.
98+
bin : Python's built-in binary representation generator of an integer.
99+
100+
Notes
101+
-----
102+
:obj:`dpnp.binary_repr` is equivalent to using :obj:`dpnp.base_repr` with
103+
base 2, but significantly faster.
104+
105+
Examples
106+
--------
107+
>>> import numpy as np
108+
>>> np.binary_repr(3)
109+
'11'
110+
>>> np.binary_repr(-3)
111+
'-11'
112+
>>> np.binary_repr(3, width=4)
113+
'0011'
114+
115+
The two's complement is returned when the input number is negative and
116+
`width` is specified:
117+
118+
>>> np.binary_repr(-3, width=3)
119+
'101'
120+
>>> np.binary_repr(-3, width=5)
121+
'11101'
122+
123+
"""
124+
125+
return numpy.binary_repr(num, width)
126+
127+
61128
_BITWISE_AND_DOCSTRING = """
62129
Computes the bitwise AND of the underlying binary representation of each
63130
element `x1_i` of the input array `x1` with the respective element `x2_i`

0 commit comments

Comments
 (0)