Last active
March 21, 2018 06:08
-
-
Save ollien/fa0e8fe471b45cdd4980cf63e63c7cf4 to your computer and use it in GitHub Desktop.
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
import sys | |
def convertToBinaryString(num): | |
if num == 0: | |
return "0" | |
result = "" | |
prevNum = 0 | |
while abs(num) > 0: | |
isOdd = num % 2 != 0 | |
result = str(int(isOdd)) + result | |
prevNum = num | |
num //= 2 | |
# 0 // 2 == 0, thus we terminate | |
if prevNum == num: | |
break | |
if num < 0: | |
return "-" + result | |
else: | |
return result | |
def bitwiseAdd(num1, num2): | |
if num1 == 0: | |
return num2 | |
elif num2 == 0: | |
return num1 | |
uncommonBits = num1 ^ num2 | |
commonBits = num1 & num2 | |
# 0 + 0 = 0 | |
# 0 + 1 = 1 | |
# 1 + 0 = 1 | |
# 1 + 1 = 10 | |
# Thus, we will only ever have to shift over once for carried bits | |
carriedBits = commonBits << 1 | |
return bitwiseAdd(uncommonBits, carriedBits) | |
def prettyPrintSum(num1, num2, decSum): | |
binaryTop = convertToBinaryString(num1) | |
binaryBottom = convertToBinaryString(num2) | |
# Swap the numbers if the lengths are different. | |
# It's nicer if the longer number is on top. | |
if len(binaryBottom) > len(binaryTop): | |
binaryTop, binaryBottom = binaryBottom, binaryTop | |
binarySum = convertToBinaryString(decSum) | |
problemSpacing = " " * (len(binaryTop) - len(binaryBottom)) | |
answerSpacing = " " * (abs(len(binaryTop) + 2 - len(binarySum))) | |
dashes = "-" * (len(binaryTop) + 2) | |
print(f" {binaryTop}") | |
print(f"+ {problemSpacing}{binaryBottom}") | |
print(dashes) | |
print(f"{answerSpacing}{binarySum}") | |
print(f"\nDec: {decSum}") | |
if __name__ == "__main__": | |
if len(sys.argv) < 3: | |
print("Usage: bitwise_add.py num1 num2") | |
else: | |
dec1 = int(sys.argv[1]) | |
dec2 = int(sys.argv[2]) | |
binarySum = bitwiseAdd(dec1, dec2) | |
prettyPrintSum(dec1, dec2, binarySum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment