2

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
0

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

4 Comments

Why doesn't $display(a.sum()+16'd0) works in this case ?
Because sum() is a function call and the return value calculation is in an independent context from where the result expression gets used. You are thinking as if the sum equation was in-lined with the + 16'd0
Hey @dave From above mentioned method, I am getting sum as 304 instead of 560. Link:- edaplayground.com/x/32BU
Because 500 gets truncated to 244.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.