2016-11-17 47 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