Created
April 7, 2014 23:56
-
-
Save if1live/10075023 to your computer and use it in GitHub Desktop.
Implement shift operator without multiplication,division,bit operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#-*- coding: utf-8 -*- | |
def left_shift(n): | |
return n + n | |
def is_bit_on(n, bit): | |
a = n % bit | |
b = n % left_shift(bit) | |
if not b: | |
return False | |
if b - a == 0: | |
return False | |
return True | |
def right_shift(n): | |
a = 1 | |
b = 2 | |
retval = 0 | |
while n > a: | |
if is_bit_on(n, b): | |
retval += a | |
a = left_shift(a) | |
b = left_shift(b) | |
return retval | |
if __name__ == '__main__': | |
for x in range(255): | |
assert (x << 1) == left_shift(x), "left shift : {}, {}".format(x << 1, left_shift(x)) | |
assert (x >> 1) == right_shift(x), "right shift : {}, {}".format(x >> 1, right_shift(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment