Verilog 刷题笔记(05)
41. A "population count" circuit counts the number of '1's in an input vector. Build a population count circuit for a 255-bit input vector.
1 module top_module( 2 input [254:0] in, 3 output [7:0] out ); 4 5 //“popcount”电路计算输入向量中“1”的数量。为 255 位输入向量构建人口计数电路。 6 always@(*) 7 begin 8 out = 0; 9 for(int i = 0;i < 255;i++) 10 out = out +in[i]; 11 end 12 13 endmodule
42. Create a 100-bit binary ripple-carry adder by instantiating 100 full addres. The adder adds two 100-bit numbers and a carry-in to produce a 100-bit sum and carry out. To encourage you to actually instantiate full adders, also output the carry-out from each full adder in the ripple-carry adder. cout[99] is the final carry-out from the last full adder, and is the carry-out you usually see.
1 // Adder-100i 方法一 2 module top_module( 3 input [99:0] a, b, 4 input cin, 5 output [99:0] cout, 6 output [99:0] sum ); 7 8 integer i; 9 10 always @ (*) begin 11 for(i = 0; i < 100; i = i + 1) begin 12 if(i == 0) 13 {cout[i],sum[i]} = a[i] + b[i] + cin; 14 else 15 {cout[i],sum[i]} = a[i] + b[i] + cout[i-1]; 16 end 17 end 18 19 endmodule 20 21 22 // Adder100i 方法二 23 module top_module( 24 input [99:0] a,b, 25 input cin, 26 output [99:0] cout, 27 output [99:0] sum 28 ); 29 30 generate 31 genvar i; 32 for(i = 0; i < 100; i = i + 1) begin:addr100 33 if(i == 0) 34 assign {cout[i],sum[i]} = a[i] + b[i] + cin; 35 //Error: {cout[i],sum[i]} = a[i] + b[i] + cin; 36 else 37 assign {cout[i],sum[i]} = a[i] + b[i] + cout[i-1]; 38 //Error: {cout[i],sum[i]} = a[i] + b[i] + cout[i-1]; 39 end 40 endgenerate 41 42 endmodule
43. 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.
1 //BCD-Adder:generate-for方法 2 3 module top_module( 4 input [399:0] a, b, 5 input cin, 6 output cout, 7 output [399:0] sum ); 8 9 10 wire[99:0] cout1; 11 bcd_fadd add0(.a(a[3:0]), 12 .b(b[3:0]), 13 .cin(cin), 14 .cout(cout1[0]), 15 .sum(sum[3:0]) 16 ); 17 18 //这题题目要求只能用generate-for来做 19 genvar i; 20 generate 21 for( i = 0 ; i<=99 ; i = i + 1)begin:bcd_fadder 22 bcd_fadd inst( 23 .a(a[4*i+3:4*i]), 24 .b(b[4*i+3:4*i]), 25 .cin(cout1[i-1]), 26 .sum(sum[4*i+3:4*i]), 27 .cout(cout1[i]) 28 ); 29 end 30 endgenerate 31 assign cout = cout1[99]; 32 33 endmodule 34 35 //这段代码,我觉得写的没问题,但是编译不通过,报错如下: 36 //Error (10232): Verilog HDL error at top_module.v(23): index -1 cannot fall outside the declared range [99:0] for vector "cout1" 37 //File: /home/h/work/hdlbits.3553395/top_module.v Line: 23