Help with Constraint

Hi ,

How to write a constraint for 32 bit data to get this type of sequence 100100100…?

I have used $countones but it will randomly set the bit.

In reply to maaroop:

Why do you need to constraint top set something that is not random? And how does that pattern fit into 32-bits?

In reply to dave_59:

Hi Dave,

I want to set the bit in these combination for a packet of data.
1st-4th-7th-10th-13th-16th-19th bit ,
3rd-6th,9th-12th-15th-18th soon

basically I want to set one bit to 1’b1 and then next two bits should be zero.

This is the pattern :32’b0100100100100100100100,
32’b0000100100100100100100100100,

In reply to maaroop:

You can use the following constraint, to meet your requirement:

    
    rand bit[31:0] data;
    rand int i;
  
    constraint data_c {
      i >=0 && i <= 31;
      foreach(data[j])
        if(j < i) data[j] == 0; 
        else if(j==i) data[j] == 1;
        else if((j-i)%3 == 0) data[j] == 1;
        else data[j] == 0;
    }

In reply to S.P.Rajkumar.V:

Thanks Rajkumar

In reply to maaroop:

You could have simply done

data = {33/3{3’b100}};

In reply to dave_59:

Thanks Dave.

I have one question :
Value is fixed here, can we write one line code to implement like this

000100100100…
0000000001001001001
so, randomly it should pick nth bit.

In reply to maaroop:

module tb();

class abc;

rand bit[31:0]data;

constraint c{ foreach(data[i])
       
  if(i%3==0)
    data[i]==1;
             else
               data[i]==0;
            }

endclass

abc d;

initial
begin
d=new();
assert(d.randomize());

  $display("value of data =%b",d.data);
  
  $finish;
  
end

endmodule

  ////////////////////output///////////////////////////////

value of data =01001001001001001001001001001001

In reply to maaroop:

Hi ,
How to write a constraint for 32 bit data to get this type of sequence 100100100…?
I have used $countones but it will randomly set the bit.

module tb();

class rohith;

rand bit[26:0]data;
//constraint k{data[0]=1’b0;}

constraint c{ foreach(data[i])

if(i%3==0)
data[i]==0;
else if(i%3==1)
data[i]==0;
else if(i%3==2)
data[i]==1;
}
endclass

rohith k;

initial
begin
k=new();
assert(k.randomize());

$display(“value of data =%b”,k.data);

$finish;

end
endmodule

OUTPUT:value of data =100100100100100100100100100

How about the best of both worlds?


// Code your testbench here
// or browse Examples
module tb();

  class abc;
    rand bit [2:0] pattern;
    bit [31:0] data;
    constraint single_bit { $countones(pattern) == 1; }
    
    function void post_randomize();
      data = {(33/3){pattern}}; // I'm having trouble explicitly casting to 32 bits, but it still works...
    endfunction
  endclass

  abc d;

  initial begin
    d=new();
    repeat (10) begin
      assert(d.randomize());
      $display("value of data =%b",d.data);
    end
    $finish;
end
endmodule

Working example on EDAPlayground

In reply to h2dkb:

Thank you.