2016-11-17 45 views
1

我想计算打包数组中的个数。我想出了以下代码: https://www.edaplayground.com/x/2Va6计数位数组中的个数

我认为这可以做得更容易。任何建议?

typedef bit bit6_t[5:0]; 

module test_rand; 
    bit [5:0] mask_packed; 
    bit mask_packed_bit[5:0]; 
    int mask_unpacked[5:0]; 
    initial begin 
     mask_packed = $urandom_range(((2**6)-1),0); 
     mask_packed_bit = bit6_t'(mask_packed); 
     foreach (mask_packed_bit[i]) begin mask_unpacked[i] = int'(mask_packed_bit[i]); end 
     $display("*********************************"); 
     $display("mask_packed = %p",mask_packed); 
     $display("mask_unpacked  = %p",mask_unpacked); 
     $display("mask_unpacked.sum = %p",mask_unpacked.sum()); 
     $display("*********************************"); 
    end 
endmodule 

回答

2

你可以尝试以下

typedef bit bit6_t[5:0]; 

module test_rand; 
    bit [5:0] mask_packed; 
    bit6_t mask_unpacked; 
    initial begin 
     mask_packed = $urandom_range(((2**6)-1),0); 
     mask_unpacked = bit6_t'(mask_packed); 
     $display("*********************************"); 
     $display("mask_packed = %p",mask_packed); 
     $display("mask_unpacked = %p",mask_unpacked); 
     $display("mask_unpacked.sum = %p",mask_unpacked.sum() with (int'(item))); 
     $display("*********************************"); 
    end 
endmodule 

工作例如:https://www.edaplayground.com/x/5cXx

3

1)对于纯Verilog代码:

你最后隐含$投以“廉政是不必要的。由于您只想总和,您可以:

typedef bit bit6_t[5:0]; 

module test_rand; 
    bit [5:0] mask_packed; 
    bit mask_packed_bit[5:0]; 
    int sum = 0; 
    initial begin 
     mask_packed = $urandom_range(((2**6)-1),0); 
     mask_packed_bit = bit6_t'(mask_packed); 
     foreach (mask_packed_bit[i]) begin sum += mask_packed_bit[i]; end 
     $display("*********************************"); 
     $display("mask_packed = %p",mask_packed); 
     $display("mask_packed_bit = %p",mask_packed_bit); 
     $display("sum = %p",sum); 
     $display("*********************************"); 
    end 
endmodule 

工作例如:https://www.edaplayground.com/x/5ZTW

2)如果你正在使用SystemVerilog的,你可以使用简单$ countones功能。

module test_rand; 
    bit [5:0] mask_packed; 
    initial begin 
     mask_packed = $urandom_range(((2**6)-1),0); 
     $display("*********************************"); 
     $display("mask_packed = %p",mask_packed); 
     $display("countones = %p", $countones(mask_packed)); 
     $display("*********************************"); 
    end 
endmodule 

工作例如:https://www.edaplayground.com/x/2Nsd