Constraint to generate gray code

Hi All,

I would like to generate gray code pattern:
0 1 3 2 6 7 5 4

I have tried with the following code, but could not get the above pattern, please suggest.

module p1;
  class c1;
    rand bit [2:0] gray;
    bit [2:0] res;
    function void post_randomize();
      foreach (gray[k]) begin
        gray[2] = gray[2];
        gray[1] = gray[1] ^ gray[2];
        gray[0] = gray[0] ^ gray[1];
      end
      res = {gray[2], gray[1], gray[0]};
      $display("gray output %0d", res);
    endfunction
  endclass
  c1 obj;
  initial begin
    obj = new;
    repeat (8)
    obj.randomize();
  end
endmodule

Thank You,

In reply to Thirumalesh Kumar:
If you want all the gray code in the order , you should randomize in a single shot ( code given below ) . Your logic to convert Binary to Gray code is correct in post_randomize but variable gray will randomize to any values . Printing variable gray at the start of post_randomize will give you the clear picture.


    rand bit [2:0] gray[8];

    constraint c_gray_values {
        foreach(gray[ii]) {
            gray[ii] = { ii[2], ii[2]^ii[1], ii[1]^ii[0] };
        }
    }

    function void post_randmomize();
        foreach(gray[ii])
            $display("%0d", gray[ii]);
    endfunction


1 Like