Rottenengg
Rottenengg

Reputation: 115

Array.sum() returns unexpected value

I'm trying to use the sum method of an array. I stored the return value of the method into an integer inside a function. Why am I getting the output as 48 instead of 560?

program test;

class check2;
logic [7:0] a [3:0] = '{10,20,30,500};

function void dis();
  int unsigned ch;
  ch = a.sum()+16'd0;
  $display(ch);
endfunction
endclass

check2 c;

initial begin
  c = new;
  c.dis;
end
endprogram

Upvotes: 2

Views: 4960

Answers (2)

dave_59
dave_59

Reputation: 42698

The result of the a.sum() method is the same type width of each element of the array. You can cast each element to a larger size using the with clause.

ch = a.sum(item) with (int'(item));

Upvotes: 3

toolic
toolic

Reputation: 62164

The array bit width is not large enough to accommodate the value 500. 500 (decimal) is equal to 0x1F4 (hex), which requires 9 bits. But, you only specify 8 bits ([7:0]). This means 500 gets converted to 0xF4, or 244 (decimal).

Also, the array bit width is not large enough to accommodate the sum of the array values (560). 560 requires 10 bits.

So, you get 48 because the sum of 10,20,30,244 is 304, which is 0x130 hex, which is too big for the 8-bit sum. So, 0x130 becomes 0x30, which is 48 (decimal).

Using logic [9:0] a [3:0] will give you an output of 560.

program test;

class check2;
    logic [9:0] a [3:0] = '{10,20,30,500};

    function void dis();
        int unsigned ch;
        ch = a.sum()+16'd0;
        $display(ch);
    endfunction
endclass

check2 c;

initial begin
    c = new;
    c.dis();
end
endprogram

Upvotes: 1

Related Questions