How can you randomize a 32 bit variable using constraints so that only 2 bits are set Without using $countones()? Also, can you generalize the solution for an n bit set case?
In reply to totochan1985:
I am sure there are many approaches to this. One way is the below :
module test();
bit arr[32];
bit [31:0] rand_var;
initial begin
arr[0] = 1;
arr[1] = 1;
arr.shuffle();
foreach(arr[i]) rand_var[i] = arr[i];
$display("%b", rand_var);
end
endmodule
To generalize, use a parameter for the size.
Generic solution using constraint :
int N ; // Non-random property so user can change it at run-time b4 calling randomize()
rand bit [31:0] v ;
constraint C2 {
N == ((v>>31)&1) + ((v>>30)&1) + ((v>>29)&1) + ... +((v>>6)&1) + ((v>>5)&1) + ((v>>4)&1) + ((v>>3)&1) + ((v>>2)&1) + ((v>>1)&1) + ((v>>0)&1);
}