Given a byte b of 8 bits, the following formula returns the bits of b “swapped” (0 and 7 are swapped, 1 and 6 are swapped, etc.):
(b * 0x0202020202 & 0x010884422010) % 1023
When I have a function implementing this hack, namely
def reverseBits(b):
return (b * 0x0202020202 & 0x010884422010) % 1023
then I get an overflow:
OverflowError: cannot fit ‘long’ into an index-sized integer
How can I implement the bit-swapping hack in Python?
This seems to work as you expect:
Prints:
This algorithm (and others) are found here. As stated, this method only works for a BYTE, so you will need to use another method for a larger bit pattern.
Edit
BTW: You can do bit reversal without any fear of overflow or math problems and for larger bit fields by using string manipulation:
Then convert back to an int this way: