Array.sum()Gotcha

时间:2017-09-13 14:54:51

标签: system-verilog

尝试实现数组的sum方法。将方法的返回值存储到函数内的Integer中。为什么我的输出为48而不是560?

      dataArrange = {}

      for g in groups:  # groups is just a list of groups eg CS10, CS9
            for i in FinalDict: # the data from which i'm putting the stuff to grs
                weekdet = []
                for b in FinalDict[i]['lectures']:
                    lectdetails = []
                    if b[0] == 'Remedial Class':
                        slot = b[1]['slot']
                    else:
                        slot = b[3]['slot']
                        subject = b[0]
                        teacherName = b[1]
                        venue = b[2]
                        lectdetails = {'subject': subject, 'teacherName': teacherName, 'venue': venue}

                    try:

                        if ShortCode[lectdetails['subject']] in ElectiveStuff:
                            continue

                    except IndexError:
                        continue

                    if not lectdetails:
                        weekdet.append({slot: "Remedial Class"})
                    else:
                        weekdet.append({slot: lectdetails})

                dataArrange.update({i: weekdet})
            grs.append({g: dataArrange})

        with open('stuff.txt', 'w') as g:  # here we wrote grs in a file which makes me sad though it solves the problem
            g.write(json.dumps(grs))

2 个答案:

答案 0 :(得分:2)

a.sum()方法的结果与数组中每个元素的类型宽度相同。您可以使用with子句将每个元素强制转换为更大的大小。

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

答案 1 :(得分:1)

数组位宽不足以容纳值500. 500(十进制)等于0x1F4(十六进制),需要9位。但是,您只需指定8位([7:0])。这意味着500转换为0xF4或244(十进制)。

此外,阵列位宽不足以容纳数组值的总和(560)。 560需要10位。

所以,你得到48,因为10,20,30,244的总和是304,这是0x130十六进制,这对于8位总和来说太大了。因此,0x130变为0x30,即48(十进制)。

使用logic [9:0] a [3:0]会输出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