Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing bits of Python integer

Given a decimal integer (eg. 65), how does one reverse the underlying bits in Python? i.e.. the following operation:

65 → 01000001 → 10000010 → 130 

It seems that this task can be broken down into three steps:

  1. Convert the decimal integer to binary representation
  2. Reverse the bits
  3. Convert back to decimal

Steps #2 and 3 seem pretty straightforward (see this and this SO question related to step #2), but I'm stuck on step #1. The issue with step #1 is retrieving the full decimal representation with filling zeros (ie. 65 = 01000001, not 1000001).

I've searched around, but I can't seem to find anything.

like image 843
David Chouinard Avatar asked Oct 01 '12 22:10

David Chouinard


People also ask

How do you flip a bit of a number?

Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number.


1 Answers

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.

like image 144
nneonneo Avatar answered Sep 22 '22 06:09

nneonneo