输入信号a,b,sel,输出信号y,当sel = 1时,y = a,当sel = 0时,y = b;
module top(a,b,sel,y);
input a,b,sel;
output y;
assign y = (sel & a) | (~sel & b);
//assign y = sel ?a : b;
endmodule
module test(
);
reg[2:0] absel;
wire y;
top f(.a(absel[0]),.b(absel[1]),.sel(absel[2]),.y(y));
initial begin
absel = 0;
#100 $stop;
end
always #10 absel = absel + 1;
endmodule
创建一个16位宽的9对1多路复用器。sel = 0选择a,sel = 1选择b,依此类推。对于未使用的情况(sel = 9至15),将所有输出位设置为“ 1”。
创建9个位宽为16的输入信号,一个输入信号sel,一个输出信号y,根据sel的值选择输入信号
创建一个1位宽的256:1多路复用器。256个输入全部打包到单个256位输入向量中。sel = 0应该选择in [0],sel = 1选择in [1]的比特,sel = 2选择in [2]的比特,依此类推。
module top(x,sel,y);
input[255:0] x;
input[7:0] sel;
output y;
assign y = x[sel];
endmodule
module test(
);
reg[255:0]x;
reg[7:0] sel;
wire y;
top f(.x(x),.sel(sel),.y(y));
initial begin
x <= 256'd7;
sel <= 0;
#3000 $stop;
end
always begin
#10 x <= x + 5;sel <= sel + 1;
end
endmodule
给定一个八位二进制数,求出其1的个数
module sum(x,y);
input[7:0] x;
output y;
reg[3:0] y;
integer i;
always @(*)begin
y = 4'd0;
for(i=0;i<8;i = i+1)begin
if(x[i] == 1)
y = y + 1;
end
end
endmodule
module test(
);
reg[7:0] x;
wire[3:0] y;
sum f(.x(x),.y(y));
initial begin
x = 0;
#3000 $stop;
end
always #10 x = x + 1;
endmodule
创建一个半加法器。半加法器将两个位相加(无进位),并产生总和与进位。
相当于模2加,但要记录进位
module top(a,b,cout,sum);
input a,b;
output cout,sum;
assign sum = a ^ b;
assign cout = a & b;
//等价于assign {cout,sum} = a + b;
endmodule
module test(
);
reg [1:0] ab;
wire cout,sum;
top f(.a(ab[0]),.b(ab[1]),.cout(cout),.sum(sum));
initial begin
ab = 0;
# 50 $stop;
end
always #10 ab = ab + 1;
endmodule
创建一个完整的加法器。一个全加法器将三个位(包括进位)相加,并产生一个总和与一个进位。
module top(a,b,cin,cout,sum);
input a,b,cin;
output cout,sum;
assign sum = a ^ b ^ cin;
assign cout = (a & b)|((a | b) & cin);
/*
当a和b都为1时,无论cin为1或0,cout都等于1
又或a和b中有一个为1且cin为1,cout也等于1
*/
endmodule
module test(
);
reg[2:0] N;
wire cout,sum;
top f(.a(N[2]),.b(N[1]),.cin(N[0]),.cout(cout),.sum(sum));
initial begin
N = 0;
#100 $stop;
end
always #10 N = N +1;
endmodule