Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Design Example

SystemVerilog Control Flow & Loops

A parameterized priority encoder driven by a for-loop testbench that walks one-hot inputs and checks the priority cases.

Open in IDE
testbench.sv
module tb_priority_encoder();
    parameter WIDTH = 8;
    
    logic [WIDTH-1:0] req;
    logic [$clog2(WIDTH)-1:0] grant;
    logic valid;
    
    // Instantiate DUT
    priority_encoder #(.WIDTH(WIDTH)) dut (
        .req(req),
        .grant(grant),
        .valid(valid)
    );
    
    initial begin
        $display("=== Priority Encoder Testbench ===");
        
        // Test case 1: No requests
        req = 8'b00000000;
        #10;
        $display("req=%b, grant=%d, valid=%b", req, grant, valid);
        
        // Test case 2: Single requests
        for (int i = 0; i < WIDTH; i++) begin
            req = 1 << i;
            #10;
            $display("req=%b, grant=%d, valid=%b", req, grant, valid);
        end
        
        // Test case 3: Multiple requests (priority test)
        req = 8'b11110000; #10;
        $display("req=%b, grant=%d, valid=%b (should be 7)", req, grant, valid);
        
        req = 8'b00001111; #10;
        $display("req=%b, grant=%d, valid=%b (should be 3)", req, grant, valid);
        
        req = 8'b10101010; #10;
        $display("req=%b, grant=%d, valid=%b (should be 7)", req, grant, valid);
        
        // Test case 4: All requests
        req = 8'b11111111; #10;
        $display("req=%b, grant=%d, valid=%b (should be 7)", req, grant, valid);
        
        $finish;
    end
  
  	initial begin
      $dumpvars;
      $dumpfile("dump.vcd");
    end
endmodule
design.sv
module priority_encoder #(parameter WIDTH = 8) (
    input  logic [WIDTH-1:0] req,
    output logic [$clog2(WIDTH)-1:0] grant,
    output logic valid
);

    always_comb begin
        grant = '0;
        valid = 1'b0;
        
        // Process from LOW to HIGH priority, so higher index overwrites lower
        for (int i = 0; i < WIDTH; i++) begin
            if (req[i]) begin
                grant = i;
                valid = 1'b1;
            end
        end
    end

endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.