学习:
Verilog has a ternary conditional operator ( ? : ) much like C:
(condition ? if_true : if_false)
This can be used to choose one of two values based on condition (a mux!) on one line, without using an if-then inside a combinational always block.
Examples:
(0 ? 3 : 5) // This is 5 because the condition is false.
(sel ? b : a) // A 2-to-1 multiplexer between a and b selected by sel.
always @(posedge clk) // A T-flip-flop.
q <= toggle ? ~q : q;
always @(*) // State transition logic for a one-input FSM
case (state)
A: next = w ? B : A;
B: next = w ? A : B;
endcase
assign out = ena ? q : 1'bz; // A tri-state buffer
((sel[1:0] == 2'h0) ? a : // A 3-to-1 mux
(sel[1:0] == 2'h1) ? b :
c )
练习:
Given four unsigned numbers, find the minimum. Unsigned numbers can be compared with standard comparison operators (a < b). Use the conditional operator to make two-way min circuits, then compose a few of them to create a 4-way min circuit. You'll probably want some wire vectors for the intermediate results.
译:
给定四个无符号数字,找出其中的最小值。无符号数字可以使用标准比较运算符进行比较(a < b)。使用条件运算符来制作双向最小值电路,然后组合几个这样的电路来创建一个四路最小值电路。你可能需要一些线矢量来存储中间结果。
module top_module (
input [7:0] a, b, c, d,
output [7:0] min);//
wire [7:0]buf1,buf2,buf3;
assign buf1 = (a>b)?b:a;
assign buf2 = (c>d)?d:c;
assign buf3 = (buf1 > buf2)?buf2:buf1;
assign min = buf3;
endmodule
运行结果: