How do I vary the lower index of a variable assignment?

Viewed 111

I want to make an assignment to a variable with a variable lower index. This is what I want to do:

int i;
logic [63:0] data;

i = someCalculatedNumber;
data[63:(i*8)] = 'h0;

I know this won't compile. What is the best method to make this assignment?

2 Answers

One way is to use a for loop:

module tb;

int i; 
logic [63:0] data;

initial begin
    data = '1;
    $displayh(data);

    i = 7;
    for (int j=63; j>=(i*8); j--) data[j] = 0;
    $displayh(data);

    i = 2;
    for (int j=63; j>=(i*8); j--) data[j] = 0;
    $displayh(data);
end
endmodule

Output:

ffffffffffffffff
00ffffffffffffff
000000000000ffff

You can wrap the code in a function.

If you are looking to zero-out the LSBs, then this should do it for you

data &= '1 << i*8;

or more readable

data = data & ('1 << i*8);

And if that's not exactly what you need, you can still use '1 << i*8 or its complement as a mask to select the portion of data you want to modify.

Related