Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

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.

Answer*

Draft saved
Draft discarded
Cancel
4
  • FYI: the link is now broken. Is this function limited to ints or will it work on numbers of type bignum? Commented Mar 25, 2019 at 2:52
  • 1
    Since the link is broken, the same procedure can be found here with a bit more information: stackoverflow.com/a/30002555/9439097 Commented May 2, 2020 at 18:03
  • This works, but is limited to 32-bit integers. Extending it to different-sized integers is possible (following the pattern) but not trivial for non-powers-of-two. Commented Aug 15, 2024 at 1:10
  • graphics.stanford.edu/~seander/bithacks.html Commented Jan 19, 2025 at 15:42

lang-py

AltStyle によって変換されたページ (->オリジナル) /