SV Constraint Question - Keeping 1s together

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
1 Like