[Numpy-discussion] int to binary
Daniele Nicolodi
daniele@grinta....
Mon Apr 29 13:17:41 CDT 2013
On 29/04/2013 17:15, josef.pktd@gmail.com wrote:
> Is there a available function to convert an int to binary
> representation as sequence of 0 and 1?
...
> That's the best I could come up with in a few minutes:
...
> 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
I haven't actually run a benchmark but
r = (x >> i) & 0x01
or
r = (x >>= 1) & 0x01
may be faster than
x, r = divmod(x, 2)
Cheers,
Daniele
More information about the NumPy-Discussion
mailing list