Write a constraint to generate a number which has binary all 1s grouped together.
class sample;
rand bit [31:0] x;
rand int num_ones;
rand int shift_by;
constraint k{
num_ones inside {[0:31]};
shift_by inside{[0:31-num_ones]};
solve num_ones before shift_by;
}
function void post_randomize();
x= {num_ones{1'b1}}<<shift_by;
endfunction
endclass
module tb;
sample s;
initial begin
s = new();
repeat(20)begin
s.randomize();
$display("%b",s.x);
end
end
endmodule
Is my solution correct for this problem.
You are not allowed a variable in a concatenation replication. And you should try avoid using post_randomized if possible to you have the option having additional constraints on x.
class sample;
rand bit [31:0] x;
rand int num_ones;
rand int shift_by;
constraint k{
num_ones inside {[0:31]};
shift_by inside{[0:31-num_ones]};
x == (32'b1 << num_ones) - 1 << shift_by;
}
endclass
module top;
sample s = new;
initial repeat(10) begin
assert(s.randomize);
$display("N: %2d S: %2d. %b",s.num_ones, s.shift_by, s.x);
end
endmodule
2 Likes
Hi @dave_59
in
x == (32’b1 << num_ones) - 1 << shift_by;
we can even achevie all the one together by using (32’b1 << num_ones) this. Then is there is any need of this part " - 1 << shift_by".
Another follow up question is suppose after randomization num_ones =5 and shift by is equals to 6.
then whole solution will be
11111111111111111111111111100000 //call this as p
and -1 can be represented in 2’s compliment form is 111111111111111111111111111111 //call this as q
and then p+q will be 00000000000000000000000000011111/call this r
and now shift right r by 6.
so final x will be 00000000000000000000011111000000
I right?
32'b1
is 1 bit set, not 32 ones.