1

Given a number, such as 2, how would I reverse the bits assuming it is represented in 32-bits?

Take 1 for example, as unsigned 32-bits is 00000000000000000000000000000001 and doing the flipping we get 11111111111111111111111111111110 which in turn is 4294967294

I've tried the following but it is not working.

numElements = int(raw_input())
for i in range(0,numElements):
    x = int(raw_input())
    print int(bin(x)[:1:-1], 2)
0

1 Answer 1

3

Use XOR against a number with all 32 bits set to one:

mask = 2 ** 32 - 1
x = int(raw_input())
print format(x ^ mask, '032b')

^ is the bitwise XOR operator.

I used the format() function to produce a 0-padded 32-bit binary representation, it is far more flexible than bin().

Demo:

>>> mask = 2 ** 32 - 1
>>> format(mask, '032b')
'11111111111111111111111111111111'
>>> x = 1
>>> x ^ mask
4294967294
>>> format(x ^ mask, '032b')
'11111111111111111111111111111110'
Sign up to request clarification or add additional context in comments.

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.