①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.
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.
module top_module (
input [7:0] a, b, c, d,
output [7:0] min);//
assign min=(((c<d)?c:d)<((a<b)?a:b))?((c<d)?c:d):((a<b)?a:b);
endmodule
② Given a 100-bit input vector [99:0], reverse its bit ordering.
module top_module(
input [99:0] in,
output [99:0] out
);
always@(*) begin
for(int i=0;i<100;i++)begin
out[i]=in[99-i];
end
end
endmodule
③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.
module top_module(
input [254:0] in,
output [7:0] out );
always@(*)
begin
out=8'b00000000;//out初始化
for (int i=0;i<=254;i=i+1)
begin
if (in[i]==1'b1)
out=out+1'b1;
else
out=out+1'b0;
end
end
endmodule
④
module top_module (
input in1,
input in2,
input in3,
output out);
assign out = ~(in1^in2) ^ in3;
endmodule