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

Verilog $random

Verilog Testbench

Example of how to use $random to generate random numbers in a testbench

Open in IDE
testbench.v
module tb;
  reg [3:0] val;
  
  initial begin
    for (integer i = 0; i < 10; i += 1) begin
      // Gives a range -1:1
      val = $random % 2;
      
      // Gives a range 0:1
      //val = {$random} % 2;
      
      $display ("val=0x%0h val=%0d", val, val);
    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.