如何把十进制的数输入用二进制全加器,并以十进制输出
二进制的全加器
二进制的算法准则
在写全加器前,我们先了解二进制的算法准则。
我们设A和B是两个相加的二进制数,C是从下一位获得的进位,两书相加的和在该位的值为Sum,全加器的两个输出仍然是给上一位的进位Carry。
A–B--C | Sum–Carry |
---|---|
0–0--0 | 0–0 |
0–0--1 | 1–0 |
0–1--0 | 1–0 |
0–1--1 | 0–1 |
1–0--0 | 1–0 |
1–0--1 | 0–1 |
1–1--0 | 0–1 |
1–1--1 | 1–1 |
从上表得出,只要A、B、C中有任意两个输入的值是1,不管余下的一个输入值是多少,Carry一定会是1。即AB=1、AC=1、BC=1;即C=AB+AC+BC.
而Sum为1有四种情况,ABC、A(非B)(非C)、(非A)B(非C)、(非A)(非B)C。
那我们可以写出全加器的前一部分
def FA(a,b,c):
Carry = (a and b) or (b and c) or (a and c)#这两行代码就是上面我们总结出的逻辑式,不要看到太多就觉得自己看不懂
Sum = (a and b and c) or (a and (not b) and (not c)) or ((not a) and b and (not c)) or ((not a) and (not b) and c)
return Carry,Sum
再让我们想想我们平常做加法时,都是从个位开始计算,在计算机中也是这种方法。而当我们碰到数字不同时,会自动把缺少的那位补零,但计算机不会自己动(计算机要是什么都会自己动我就不会在这敲键盘了……)。
根据上面这句话我们可以再写一串代码。
def add(x,y):
while len(x) < len(y):#用来比较两个输入数字的长度,下面也是
x = [False] + x#这行代码就是用来补零的,下面也是
while len(x) > len(y):
y = [False] + y
L = []
Carry = False
for i in range(len(x)-1,-1,-1):#range函数从零开始计位所以减1,-1表示逆位,-1表示间距
Carry,Sum = FA(x[i],y[i],Carry)
L = [Sum] + L
return (Carry,L)
十进制如何转化成二进制输入
我们输入一个值看看
我们可以发现该函数可以输入二进制的数,但必须是列表形式,而且必须每个数占一个元素。
那么我们可以定义一个函数,首先把十进制转化成二进制,再将每个数一个个取出,加入列表中。
def Deci(E,F):
e = list(str(bin(E)))
f = list(str(bin(F)))
x = e[2:]#因为转化成二进制,前面有0b这个表示二进制的标志也会加入列表,所以我们从第三位开始算
y = f[2:]
return x,y
下图是两个代码的对比
二进制如何以十进制输出
我今天想出来可以把第二个函数的结果以一个字符串的形式输出,然后替换里面的True和False。奈斯。
前面的代码我改成了这个样子
def add(x,y):
while len(x) < len(y):
x = [False] + x
while len(x) > len(y):
y = [False] + y
L = []
Carry = False
for i in range(len(x)-1,-1,-1):
Carry,Sum = FA(x[i],y[i],Carry)
L = [Sum] + L
l = [str(i) for i in L]#把列表里的元素都改成字符串
list = ''.join(l)#把列表里的字符串合并成一个字符串
return str(Carry) + list#把两个字符串合并
def text(word,txt1 = 'True',txt2 = 'False',txt3 = '1',txt4 = '0'):
word_1 = word.replace(txt1,txt3)
word_2 = word1.replace(txt2,txt4)
return int(word_2,2)
结果没错,这里不截图了
综上所述
终于到了把所有函数合并的时刻了,开心。
def FA(a,b,c):
Carry = (a and b) or (b and c) or (a and c)#这两行代码就是上面我们总结出的逻辑式,不要看到太多就觉得自己看不懂
Sum = (a and b and c) or (a and (not b) and (not c)) or ((not a) and b and (not c)) or ((not a) and (not b) and c)
return Carry,Sum
def add(x,y):
while len(x) < len(y):
x = [False] + x
while len(x) > len(y):
y = [False] + y
L = []
Carry = False
for i in range(len(x)-1,-1,-1):
Carry,Sum = FA(x[i],y[i],Carry)
L = [Sum] + L
l = [str(i) for i in L]
list = ''.join(l)
txt = str(Carry) + list
return txt
def text(word,txt1 = 'True',txt2 = 'False',txt3 = '1',txt4 = '0'):
word_1 = word.replace(txt1,txt3)
word_2 = word_1.replace(txt2,txt4)
return int(word_2,2)
def Deci(E,F):
e = list(str(bin(E)))
f = list(str(bin(F)))
x = [int(i) for i in e[2:]]
y = [int(i) for i in f[2:]]
word = add(x,y)
coensored = text(word,txt1 = 'True',txt2 = 'False',txt3 = '1',txt4 = '0')
return coensored
呐,答案没错。这是老师给我布置得题目,十进制转化成二进制输入,把输出的二进制再转化成十进制的形式输出,我能怎么办呢。