您可以使用您在 Verilog 中描述的相同技术...使用 if 语句,它们必须位于 always 块中,如下所示:
always @ (*) begin
if (operation == 3'b000) begin
alu_result = and_result;
end else if (operation == 3'b001) begin
alu_result = or_result;
end else if (operation == 3'b010) begin
alu_result = add_result;
// ...repeat this pattern for the other operations except BEQ...
end else begin
alu_result = beq_result;
end
end
在此示例中,*_result 连线是各个操作的结果值。代码将合成到一个多路复用器,该多路复用器在各个结果值之间进行选择(取决于operation)并驱动作为最终 ALU 输出的alu_result。
对于这个应用程序,最好使用case,而不是使用if 语句,如下所示:
always @ (*) begin
case (operation)
3'b000: alu_result = and_result;
3'b001: alu_result = or_result;
3'b010: alu_result = add_result;
// ...repeat this pattern for the other operations except BEQ...
default: alu_result = beq_result;
endcase
end
如您所见,它更紧凑且易于阅读。如果编写正确,两种变体都应导致完全相同的多路复用器逻辑。请注意,在这两种变体中,alu_result 必须是 reg [31:0] 类型,因为我们在 always 块内进行分配,但如果您愿意,可以使用 wire:
alu_result = operation == 3'b000 ? and_result
: operation == 3'b001 ? or_result
: operation == 3'b010 ? add_result
// ...repeat this pattern for the other operations except BEQ...
: beq_result;
编辑
OP 指出他需要一个位级的结构化多路复用器代码。
可以用 AND、OR 和 NOT 门创建一个非常简单的多路复用器。例如,可以按如下方式创建 2 路多路复用器:
not(select_inv,select);
and(selected_signal_a,signal_a,select_inv);
and(selected_signal_b,signal_b,select);
or(selected_result,selected_signal_a,selected_signal_b);
在此示例中,select 确定 signal_a 和 signal_b 中的哪一个通过最终输出 selected_result。
您可以对多个选择位(提示:您需要三个)使用相同的模式,例如串联堆叠多个多路复用器。