Constraint to randomize such a way that consecutive 2 bits are set to 1, other bits are 0 for 16-bit variable

Viewed 460

I need to write a constraint to randomize such a way that consecutive 2 bits are set to 1, other bits are 0 (i.e. 16'b0000_0000_0011, 16'b0000_1100_0000, etc.) for a 16-bit variable.

I tried using $countones. It is working for two bits but is not working consecutive 2 bits. Its display is

# Value is 10000000000100 
# Value is 10000000010
1 Answers

One simple way is to use a random index variable which is constrained between 0 and 14, then use another constraint to set only the 2 bits of your data.

module tb;

class c;
    rand bit [ 3:0] idx;
    rand bit [15:0] data;
    constraint c0 {
        idx < 15;
        data == (3 << idx);
    }
endclass

initial begin
    c c;
    c = new();
    repeat (20) begin
        c.randomize();
        $displayb(c.data);
    end
end

endmodule

Example output:

0000110000000000
0000011000000000
0000110000000000
0110000000000000
0000110000000000
0000000000110000
0000000110000000
0000110000000000
0000110000000000
0000001100000000
0000000000000011
0000001100000000
0000110000000000
0001100000000000
0000110000000000
0000000110000000
0011000000000000
0000000000110000
0000000000110000
0000001100000000
Related