Hi, I am trying to generate a simple Packet class that has a variable length (2 to 5 bytes long) payload with an an additional constraint that the sum of all payload bytes is 100.
I tried this code in edaplayground
module test();
class pkt;
rand bit[7:0] payload[];
constraint c1 {payload.size inside{[2:5]};}
constraint c2 {payload.sum==100;}
endclass
initial begin
int i;
pkt p_h = new();
if(p_h.randomize())
for(i=0;i<p_h.payload.size;i++)
$display("Size is %0d with %0dst element is %0d", p_h.payload.size,i+1,p_h.payload[i]);
end
endmodule
The output I’m seeing is :
Size is 2 with 1st element is 163
Size is 2 with 2st element is 193
I need the sum to be 100 in decimal. But it is considering hex. Can you please suggest me what to do.
In reply to raghu_d_21:
Hi,
below should work fine , i tried in EDA playground and its giving expected results.
class payload;
rand bit[7:0] payload[];
constraint size {
payload.size() inside {[2:5]};
}
constraint sum {
payload.sum() with (int'(item)) == 100;
}
endclass
module top;
payload pd;
initial begin
pd = new();
for (int i = 0 ; i < 5; i++) begin
if (pd.randomize()) begin
foreach (pd.payload[i]) begin
$display ( "VALUE AT %0d is %0d" , i ,pd.payload[i]);
end
else $display("Randomization failed!");
end
end
endmodule
In reply to sanket2193:
we are representing each payload item with 8 bits which are sufficient to hold a sum value of 100. so why is this working only if we cast the item to be of int type in the constraint?
Because item represents the actual payload element so item width == payload array element width = 8 bits which should hold the sum 100
what am I missing here?
In reply to hsam:
Because if you add 2 8-bit numbers together, the result is an 8-bit sum. 163+193 is 8’hA3 +8’hC1 = 8’h64. You would need to cast each element to 11 bits to add 5 8-bit array elements without overflow.