3

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

This does not work

def reverseBits(self, n):
    return int(bin(n)[:1:-1], 2)
4
  • 1
    What is your actual question? Commented Apr 20, 2018 at 20:08
  • Why my first approach does not work? Commented Apr 20, 2018 at 20:09
  • please edit your post with the question Commented Apr 20, 2018 at 20:09
  • 3
    Why do you imagine your input 43261596 should be rendered in binary with six leading zeroes? Your code isn't adding any leading zeroes Commented Apr 20, 2018 at 20:12

2 Answers 2

9

Your problem is in assuming Python's bin produces a 32 bit aligned output. It doesn't; it outputs the smallest number of bits possible. Python 3's int type has an unbounded number of bits, and even in Python 2, int will auto-promote to long if it overflows the bounds of int (which is not related to the limits of C's int).

If you want it to act like a specific width, the easiest way is to use formatting tools with more control (which will also simplify your slice operation).

For example, by formatting to a fixed 32 characters wide, padding with zeroes, you get your desired result:

>>> int('{:032b}'.format(43261596)[::-1], 2)
964176192
Sign up to request clarification or add additional context in comments.

Comments

0

The answer is in the output of bin():

>>> bin(12345)
'0b11000000111001'

As you can see, it only outputs the first 14 ones and zeros. This is because it removes any leading zeros. Why does it do this? Well, python doesn't use a fixed size for integers like many other languages. The ints might be any number of bytes in practice, depending on the system and implementation.

So instead of 00000000000000001111111111111111 becoming 11111111111111110000000000000000, it becomes 1111111111111111 instead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.