I have the question to generate a random number which is 8 bits and to write a constraint so that only 4 bits are set?
Example: 8’b10101010, 8’b11110000, 8’b01010101 etc.
I have written the code as shown below. Kindly suggest me any improvements to my code which would be more simple.
class var_four;
randc bit [7:0] var_first;
constraint c1 {$onehot(var_first) == 1;};
endclass
module var_four;
initial begin
bit [7:0] temp_var;
temp_var = 8'b0;
var_four var_handle;
var_handle = new();
repeat (8) begin
repeat (4) begin
var_handle.randomize();
temp_var = temp_var | (var_handle.var_first);
$display("------------------------------------");
$display("\t temp_var = 8'b%08b",temp_var);
$display("------------------------------------");
$display("------------------------------------");
$display("var_handle.var_first = 8'b%08b", var_handle.Var_first);
$display("------------------------------------");
end
end
end
endmodule
After executing the code, I am getting the following error. Can anyone please help me with this.
Error-[SE] Syntax error
Following verilog source has syntax error :
“testbench.sv”, 22: token is ‘var_handle’
var_four var_handle;
^
changed the constraint will set the any four bits in 8 bits.
class var_four;
randc bit [7:0] var_first;
constraint c1 {$countones(var_first) == 4;}
endclass
module var_four;
initial begin
var_four var_handle;
bit [7:0] temp_var;
temp_var = 8'b0;
var_handle = new();
repeat (8) begin
repeat (4) begin
void'(var_handle.randomize());
temp_var = temp_var | (var_handle.var_first);
$display("------------------------------------");
$display("\t temp_var = 8'b%08b",temp_var);
$display("------------------------------------");
$display("------------------------------------");
$display("var_handle.var_first = 8'b%08b", var_handle.var_first);
$display("------------------------------------");
end
end
end
endmodule
In reply to kddholak:
BTW, your syntax error was because you tried to declare var_handle in the middle of a procedural begin/end block. All declarations in a block must come before any procedural statements.
class rand_4bit;
rand bit[7:0] var1;
constraint c1 {$countones(var1)==4;};
endclass
program test;
rand_4bit handle;
initial begin
handle =new();
repeat(10) begin
handle.randomize();
$display(“var1 = 8’b%08b”,handle.var1);
end
end
endprogram
This code will generate 8-bit random numbers with any of the 4 bits are set.