[Numpy-discussion] int to binary

josef.pktd@gmai... josef.pktd@gmai...
Mon Apr 29 10:15:14 CDT 2013


 Is there a available function to convert an int to binary
representation as sequence of 0 and 1?


 binary_repr produces strings and is not vectorized

>>> np.binary_repr(5)
'101'
>>> np.binary_repr(5, width=4)
'0101'
>>> np.binary_repr(np.arange(5), width=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python26\lib\site-packages\numpy\core\numeric.py", line
1732, in binary_repr
    if num < 0:
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

------------
That's the best I could come up with in a few minutes:


>>> k = 3;  int2bin(np.arange(2**k), k, roll=False)
array([[ 0.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 1.,  1.,  0.],
       [ 0.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> k = 3;  int2bin(np.arange(2**k), k, roll=True)
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  1.],
       [ 1.,  0.,  0.],
       [ 1.,  0.,  1.],
       [ 1.,  1.,  0.],
       [ 1.,  1.,  1.]])

-----------
def int2bin(x, width, roll=True):
    x = np.atleast_1d(x)
    res = np.zeros(x.shape + (width,) )
    for i in range(width):
        x, r = divmod(x, 2)
        res[..., -i] = r
    if roll:
        res = np.roll(res, width-1, axis=-1)
    return res


Josef


More information about the NumPy-Discussion mailing list