I can easily generate a random number of width 32 bits in Verilog using $random. Is there a way to generate a random number of exactly n bits (say n = 70)?

I guess I could concatenate many 32-bits random numbers, and then restrict down to the required number of bits, but that seems like a hack.

  • 3
    \$\begingroup\$ Seems like a reasonable hack to me, given the Verilog simulator will need to actually do its calculations using the underlying machine architecture, which probably deals with 32 or 64 bit words rather than single bits at a time. \$\endgroup\$
    – The Photon
    Commented Sep 3, 2012 at 15:33
  • \$\begingroup\$ See also stackoverflow.com/questions/34011576/… \$\endgroup\$ Commented Feb 23, 2017 at 17:29

1 Answer 1


If you are able to use SystemVerilog, you can randomize a number of any width. Either declare it as rand within a class, or use std::randomize. Here is a simple example:

module top;

  bit[69:0] vec;

  initial begin
    $display("vec = %070b", vec);


If you need to stick to plain old Verilog, I think the hack you suggested is the best, simplest, and possibly the only choice. I don't think there is anything in the language to help, since $random returns a 32-bit number.

If you simply want to avoid declaring new variables and explicitly concatenating them, you could do something like this.

vec[31:0]  = $random;
vec[63:32] = $random;
vec[69:64] = $random;
  • \$\begingroup\$ what does the line $display("vec = %070b", vec); \$\endgroup\$
    – ayr
    Commented May 8 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.