今天在HDLbits上练习,做到了与加法器相关的题目,在网上稍微查了一下全加器的原理,,我自己的理解是:用一个2位字符HE,把a,b,cin位加起来,得到HE=00|01|10|11这四种结果,高位cout是0就相当于不进位,是1就进位,低位sum是多少就是多少。根据这个想法写了一串代码
module add1 ( input a, input b, input cin, output sum, output cout );
wire [1:0]HE;
assign HE=a+b+cin;
assign sum=HE[0];
assign cout=HE[1];
endmodule
没有问题,编译通过了,但是看了下提示发现网站给了一个另一个算法:
module add1 ( input a, input b, input cin, output sum, output cout );
assign sum = a ^ b ^ cin;
assign cout = a&b | a&cin | b&cin;
endmodule
这个算法确实更简洁,但是需要脑子转一下弯,如sum=a ^ b ^ cin,我稍微算了一下这个式子的真值表:
a b cin a^b^cin
0 0 0 0
1 0 0 1
0 1 0 1
0 0 1 1
1 1 0 0
1 0 1 0
0 1 1 0
1 1 1 1
即当a,b,cin中同时存在1个“1”或3个“1”时,结果为1,其逻辑为:0^0=0,再与1亦或时=1,0^1=1,再与1亦或时=1,而1^1=0,此时再与0亦或时=0。
cout = a&b | a&cin | b&cin相对好懂一点,只要a,b,cin中同时存在2个“1”就要进位。
相对来说,我自己写的第一个代码更符合直觉,第二个代码显然对语法理解更深,从逻辑层面实现功能,这是初学者第一时间想不到的。