math4tots math4tots - 2 months ago 18
Python Question

Slick way to reverse the (binary) digits of a number in Python?

I am looking for a slick function that reverses the digits of the binary representation of a number.

If

f
were such a function I would have

int(reversed(s),2) == f(int(s,2))
whenever s is a string of zeros and ones starting with 1.

Right now I am using
lambda x: int(''.join(reversed(bin(x)[2:])),2)


which is ok as far as conciseness is concerned, but it seems like a pretty roundabout way of doing this.

I was wondering if there was a nicer (perhaps faster) way with bitwise operators and what not.

Answer

How about

int('{0:b}'.format(n)[::-1], 2)

or

int(bin(n)[:1:-1], 2)

The second method seems to be the faster of the two, however both are much faster than your current method:

import timeit

print timeit.timeit("int('{0:b}'.format(n)[::-1], 2)", 'n = 123456')

print timeit.timeit("int(bin(n)[:1:-1], 2)", 'n = 123456')

print timeit.timeit("int(''.join(reversed(bin(n)[2:])),2)", 'n = 123456')
1.13251614571
0.710681915283
2.23476600647