I have a 32 bit variable, I want to write a constraint which constraints the number of consecutive ones that the variable can have.
The below constraint gives the maximum number of one that the variable can have. I want to have a constraint which limits the number of consecutive 1s to 4. The other bits could be 1/0. so the $countones can be greater than 4.
I created a function which can count the number of consecutive ones in a variable, but I cannot use that function in a constraint with input as variable as variable will be solved first and then the function and it causes constraint failure.
class random;
rand bit [31:0] variable;
constraint C1 {
$countones(variable) <=4 ;
endclass
I like Dave’s method because it’s concise, but it had an off-by-one bug that allowed the 5 LSBs to be 5’b11111. Bug fix and full self-checking example here: Edit code - EDA Playground