math4tots math4tots - 1 year ago 90
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.


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 Source

How about

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


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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download