Reversing bits of Python integer Reversing bits of Python integer python python

Reversing bits of Python integer


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

You can specify any filling length in place of the 8. If you want to get really fancy,

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

lets you specify the width programmatically.


If you are after more speed, you can use the technique described inhttp://leetcode.com/2011/08/reverse-bits.html

def reverse_mask(x):    x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1)    x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2)    x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4)    x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8)    x = ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16)    return x


def reverse_bit(num):    result = 0    while num:        result = (result << 1) + (num & 1)        num >>= 1    return result

We don't really need to convert the integer into binary, since integers are actually binary in Python.

The reversing idea is like doing the in-space reversing of integers.

def reverse_int(x):    result = 0    pos_x = abs(x)    while pos_x:        result = result * 10 + pos_x % 10        pos_x /= 10    return result if x >= 0 else (-1) * result

For each loop, the original number is dropping the right-most bit(in binary). We get that right-most bit and multiply 2 (<<1) in the next loop when the new bit is added.