# [Numpy-discussion] int to binary

Sebastian Berg sebastian@sipsolutions....
Mon Apr 29 10:25:10 CDT 2013

```On Mon, 2013-04-29 at 11:15 -0400, josef.pktd@gmail.com wrote:
>  Is there a available function to convert an int to binary
> representation as sequence of 0 and 1?
>

Maybe unpackbits/packbits? It only supports the uint8 type, but you can
view anything as that (being aware of endianess where necessary). You
will also have to reshape the result, but that should not be a problem.

- Sebastian

>
>  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
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

```