Search code examples
constraintsverilogsystem-verilog

System Verilog randomize address equal to 2 to the power off


I want to constrain an address in System Verilog so that the address is equal to two the power of value. for example the generated address(16-bit) should be

addr = 0, 2, 4, 8, 16, 32 .... 32,768

The following works for me. However, I am looking for any other short and elegant way of doing it.

class two_power_addr;
  rand bit [15:0] addr;
  bit [15:0] temp;

  constraint c_addr {
    addr == temp;
  }

endclass

module tb();
  two_power_addr c;

  initial begin
    c=new();
    c.temp=0;
    c.randomize();
    $display("%0d \n", c.addr);
    c.temp=16'h2;
    for(int i=0; i<10; i++) begin      
      c.randomize();
      c.temp=c.temp<<1;
      $display("%0d \n", c.addr);
    end
  end
endmodule

Solution

  • constraint c_addr { $onehot0(addr) == 1; }