使用python模拟加法器的构造

# =============================================================================
# 答疑:李立宗
# 时间:2020.9.9
# 使用python构造基于门的加法器
# 拓展阅读:《编码:隐匿在计算机软硬件背后的语言》
# 第12章 二进制加法器
# =============================================================================
import random
def AND(a, b):
return int(a and b)

def OR(a, b):
return int(a or b)

def NAND(a, b):
return int(not AND(a, b))

def XOR(a, b):
return AND(NAND(a, b), OR(a, b))

def halfAdder(a, b):
s = XOR(a, b)
co = AND(a, b)
return s, co

def fullAdder(a, b, ci):
s, co1 = halfAdder(a, b)
s, co2 = halfAdder(ci, s)
co = OR(co1, co2)
return s, co

def adder(x, y, sub): # sub=0:add, sub=1:subtract
y = list(y)
for i in range(len(y)):
y[i] = XOR(sub, y[i])
ans = [fullAdder(int(x[7]), int(y[7]), sub)]
for i in range(6, -1, -1):
ans.insert(0, fullAdder(int(x[i]), int(y[i]), ans[0][1]))
ans.insert(0, (XOR(sub, ans[0][1]), None))
for eachBit in ans:
print(eachBit[0],end="")

def getTestString():
s=''
for i in range(1,9):
c=random.randint(0,1)
s=s+str(c)
return s


a=getTestString()
b=getTestString()
print("数值1:%s"%a)
print("数值2:%s"%b)
print("加法:",end="")
adder(a,b,0)
print()
print("减法:",end="")
adder(a,b,1)