Skip to content

Instantly share code, notes, and snippets.

@icamys icamys/reverse_bin.py
Last active Jul 16, 2018

Embed
What would you like to do?
Reverse integer in binary form
import sys
def leading_zeros(x: int):
n = 32
y = x >> 16
if y != 0:
n = n - 16
x = y
y = x >> 8
if y != 0:
n = n - 8
x = y
y = x >> 4
if y != 0:
n = n - 4
x = y
y = x >> 2
if y != 0:
n = n - 2
x = y
y = x >> 1
if y != 0:
return n - 2
return n - x
def reverse(num: int):
zeros = leading_zeros(num)
k = 32 - zeros
if k > 1:
num = (num & 0x55555555) << 1 | (num & 0xAAAAAAAA) >> 1
if k > 2:
num = (num & 0x33333333) << 2 | (num & 0xCCCCCCCC) >> 2
if k > 4:
num = (num & 0x0F0F0F0F) << 4 | (num & 0xF0F0F0F0) >> 4
if k > 8:
num = (num & 0x00FF00FF) << 8 | (num & 0xFF00FF00) >> 8
if k > 16:
num = (num & 0x0000FFFF) << 16 | (num & 0xFFFF0000) >> 16
return num
assert len(sys.argv) == 2
x: int = int(sys.argv[1])
assert 0 <= x <= 1000000000
print(reverse(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.