Created
February 27, 2013 01:09
-
-
Save vierbergenlars/5043999 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| def and(bits1, bits2): | |
| """ | |
| Executes AND operation on 2 binary numbers, like it is done internally when using & operator | |
| """ | |
| bits_out = [] | |
| while True: | |
| if i > len(bits1) && i > len(bits2): | |
| # We have past all bits in both numbers, break out of the loop now | |
| break | |
| if i < len(bits1): | |
| # There is still a bit at position i | |
| bit1 = bits1[i] | |
| else: | |
| # No more bit :(, set it to 0 | |
| bit1 = 0 | |
| # same for bits2 | |
| if i < len(bits2): | |
| bit2 = bits2[i] | |
| else: | |
| bit2 = 0 | |
| # Execute AND operation. | |
| # 1 & 1 = 1 | |
| # 1 & 0 = 0 | |
| # 0 & 1 = 0 | |
| # 0 & 0 = 0 | |
| bits_out[i] = bit1 & bit2 | |
| return ''.join(bits_out) # Just put all the little bits together to one nice string | |
This file contains hidden or 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
| def or(bits1, bits2): | |
| """ | |
| Executes OR operation on 2 binary numbers, like it is done internally when using | operator | |
| """ | |
| bits_out = [] | |
| while True: | |
| if i > len(bits1) && i > len(bits2): | |
| # We have past all bits in both numbers, break out of the loop now | |
| break | |
| if i < len(bits1): | |
| # There is still a bit at position i | |
| bit1 = bits1[i] | |
| else: | |
| # No more bit :(, set it to 0 | |
| bit1 = 0 | |
| # same for bits2 | |
| if i < len(bits2): | |
| bit2 = bits2[i] | |
| else: | |
| bit2 = 0 | |
| # Execute AND operation. | |
| # 1 | 1 = 1 | |
| # 1 | 0 = 1 | |
| # 0 | 1 = 1 | |
| # 0 | 0 = 0 | |
| bits_out[i] = bit1 | bit2 | |
| return ''.join(bits_out) # Just put all the little bits together to one nice string | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment