Can we randomize strings in systemverilog ? for example the below code is giving me the following error :-
class chk;
rand string abc;
endclass
module pg;
chk c1;
initial begin
c1=new();
c1.randomize();
$display("%s \n",c1.abc);
$finish;
end
endmodule
Errors:
cvlog: *E,RNDVBL (testbench.sv,4|17): Variables declared with the 'rand' modifier must be of an integral or class handle type
sharat
June 27, 2016, 10:19am
2
In reply to dhpant28 :
No, we cannot randomize a string variable. Here is a workaround that I could come up with for generating random strings.
class temp_c;
rand byte unsigned temp[];
constraint str_len { temp.size() == 4; } // Length of the string
constraint temp_str_ascii { foreach(temp[i]) temp[i] inside {[65:90], [97:122]}; } //To restrict between 'A-Z' and 'a-z'
function string get_str();
string str;
foreach(temp[i])
str = {str, string'(temp[i])};
return str;
endfunction
endclass
module top;
temp_c obj;
initial begin
obj = new;
obj.randomize();
$display("\nString is :%0s", obj.get_str());
end
endmodule
1 Like
In reply to sharat :
Thanks for this Code. I have one question regarding the array declaration. Over here we have made some conditions upon the numbers which are unsigned themselves. So, do we need to specify
" unsigned ". Can we not just write -
rand byte str [];
constraint condition{str.size <= 50;
foreach(str[i])
str[i] inside {[65:90], [97:122]};}
In reply to Shubhabrata :
For this example, it doesn’t matter. But if the constraints involved numbers bigger than 127, they would be treated as negative.
You can use packed vectors of 8 bits.
For example, this is a program that generate a palindrome of length 10 characters. Using constrained randomization:
module testb;
class tb;
rand bit [10][8] palindrome;
constraint palindrome_constr {
foreach(palindrome[i]) {
palindrome[i] inside {[65:90], [97:122]};
if(i<10/2){
palindrome[i] == palindrome[10-i-1];
}
else {
}
}
} ;
endclass
tb tb_object;
initial begin
tb_object = new();
repeat(10) begin
assert(tb_object.randomize());
$display("%s", tb_object.palindrome);
end
end
endmodule