使用python模擬加法器的構造
# =============================================================================
# 答疑:李立宗 [email protected]
# 時間: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)