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.
In this tutorial, we are going to learn how to reverse a given number in Python by making the reverse of digits. So let’s get started. To reverse a given number we need to follow some steps. User has to enter a value. Divide the number with 10 to remove last digit. Print the reverse number.
Divide the number with 10 to remove last digit. Print the reverse number. In this program, we create a function named reverse. The reverse function takes a number as an argument and returns the reversed number.
Reverse a Number Using Recursion 1 num = int (input ("Enter the number: ")) 2 revr_num = 0 3 def recur_reverse (num): 4 global revr_num 5 if (num > 0): 6 Reminder = num % 10 7 revr_num = (revr_num * 10) + Reminder 8 recur_reverse (num // 10) 9 return revr_num 10 revr_num = recur_reverse (num) More items...
There is an entire half chapter of Hacker's Delight devoted to this issue (Section 7-1: Reversing Bits and Bytes) using binary operations, bit shifts, and other goodies. Seems like these are all possible in Python and it should be much quicker than the binary-to-string-and-reverse methods.
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
You could do it with shift operators like this:
def revbits(x):
rev = 0
while x:
rev <<= 1
rev += x & 1
x >>= 1
return rev
It doesn't seem any faster than your method, though (in fact, slightly slower for me).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With