generate for-loop:100-digit BCD adder

You are provided with a BCD one-digit adder named bcd_fadd that adds two BCD digits and carry-in, and produces a sum and carry-out.

module bcd_fadd (
    input [3:0] a,
    input [3:0] b,
    input     cin,
    output   cout,
    output [3:0] sum );
Instantiate 100 copies of bcd_fadd to create a 100-digit BCD ripple-carry adder. Your adder should add two 100-digit BCD numbers (packed into 400-bit vectors) and a carry-in to produce a 100-digit sum and carry out.

Bcdadd100 - HDLBits (01xz.net)

 1 module top_module( 
 2     input [399:0] a, b,
 3     input cin,
 4     output [99:0]cout,
 5     output [399:0] sum );
 6     assign sum[0] = cin^ a[0] ^ b[0];
 7     assign cout[0] = (a[0]&b[0]) | (a[0]&cin) | (b[0]&cin);
 8     
 9     genvar i;
10     generate
11         for(i=1;i<100;i=i+1)begin: adder
12             assign sum[i] = cout[i-1]^a[i]^b[i];
13             assign cout[i] = (a[i]&b[i]) | (a[i]&cout[i-1]) | (b[i]&cout[i-1]);
14         end   //没看懂,也没成功运行
15     endgenerate
16 
17 endmodule

 再写:

module top_module( 
    input [399:0] a, b,
    input cin,
    output cout,
    output [399:0] sum );
	wire [99:0] cout_temp;
	genvar i;
    generate
        for(i=0;i<100;i++) begin:bcd_fadd
            if(i == 0)
                bcd_fadd bcd_inst(a[3:0],b[3:0],cin,cout_temp[0],sum[3:0]);
            else
                bcd_fadd bcd_inst(a[4*i+3:4*i],b[4*i+3:4*i],cout_temp[i-1],cout_temp[i],sum[4*i+3:4*i]);
        end
        assign cout=cout_temp[99];
    endgenerate

endmodule

  此代码可以运行成功,其实也是基于上一题的基础

因为有一个[i-1]的存在,所以需要对i=0的情况单独讨论

然后反复例化调用,从i=0到i=1……一直到i=99,然后输出

又因为这些迭代值如果一直及存在一个一位的数据中,可能会出现问题,所以设定了一个wire [99:0] cout_temp帮忙存储值,再导出即可

posted @ 2023-04-20 11:26  江左子固  阅读(57)  评论(0)    收藏  举报