Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 866
math4tots Avatar asked Mar 02 '13 22:03

math4tots


People also ask

How to make reverse of digits in Python?

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.

How to remove last digit of a number in Python?

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.

How to reverse a number using recursion in Python?

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...

Is it possible to reverse bits and bytes in Python?

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.


2 Answers

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
like image 65
arshajii Avatar answered Oct 14 '22 16:10

arshajii


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).

like image 28
Kelsey Avatar answered Oct 14 '22 18:10

Kelsey