How do you reverse the significant bits of an integer in python?

bit-manipulation, python

Solution

reversed_ = sum(1<<(numbits-1-i) for i in range(numbits) if original>>i&1)

Problem

What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it? For example I have the numbers 1,2,5,15 and I want to reverse the bits like so: ``` original reversed 1 - 0001 - 1000 - 8 2 - 0010 - 0100 - 4 5 - 0101 - 1010 - 10 15 - 1111 - 1111 - 15 ``` Given that these numbers are 32 bit integers how should I do this in python? The part I am unsure about is how to move individual bits around in python and if there is anything funny about using a 32bit field as an integer after doing so. PS This isn't homework, I am just trying to program the solution to a logic puzzle.

Original source

Related problems