System Verilog (6) 陣列操作
阿新 • • 發佈:2022-03-31
SV支援對陣列內變數的 定位locator、排序ordering 和縮位 reduction
(1) 定位
find with, find_first with, find_last with 找的是陣列內元素
find_index with, find_first_index with , find_last_index with 找的是索引號
檢視程式碼
檢視程式碼
module array_locator; int array[9] = '{1,2,3,4,5,6,7,8,9}; int res[$]; initial begin res= array.find (x) with (x>3); $display("find x with x>3: %p", res); res= array.find_first with (item<9 & item>2); $display("find_first with (item<9 & item>2): %p",res); res= array.find_last with (item<9 & item>=3); $display("find_last with item<9 & item>=3: %p",res); res= array.find_index with (item==3); $display("find_index with item==3: array[%0d]=3",res[0]); res= array.find_first_index(x) with (x>3); $display("find_first_index x with x>3: array[%0d]>3",res[0]); res= array.find_last_index(x) with (x<=4); $display("find_last_index x with x<=4: array[%0d]<=4",res[0]); end endmodule
編譯結果
# Loading sv_std.std # Loading work.array_locator(fast) # # vsim -voptargs=+acc=npr # run -all # find x with x>3: '{4, 5, 6, 7, 8, 9} # find_first with (item<9 & item>2): '{3} # find_last with item<9 & item>=3: '{8} # find_index with item==3: array[2]=3 # find_first_index x with x>3: array[3]>3 # find_last_index x with x<=4: array[3]<=4 # exit # End time: 02:48:51 on Mar 31,2022, Elapsed time: 0:00:01 # Errors: 0, Warnings: 0 Done
(2)排序 orderig
在寫這段程式碼的時候發現了一個有意思的細節,SV內建的陣列排序函式都是空函式(void function),因此沒有返回值,就不能像上面一樣在操作過後把它賦值給一個佇列,這裡只需要直接呼叫函式(.sort, .rsort, .reverse, .shuffle),然後列印陣列即可!
檢視程式碼
module array_ordering; int array[8]='{1,2,3,4,5,6,7,8}; initial begin array.sort; $display("sort: %p",array); array.rsort; $display("rsort: %p",array); array.reverse; $display("reverse: %p",array); array.shuffle; $display("shuffle: %p",array); end endmodule
編譯結果
# Loading sv_std.std
# Loading work.array_ordering(fast)
#
# vsim -voptargs=+acc=npr
# run -all
# sort: '{1, 2, 3, 4, 5, 6, 7, 8}
# rsort: '{8, 7, 6, 5, 4, 3, 2, 1}
# reverse: '{1, 2, 3, 4, 5, 6, 7, 8}
# shuffle: '{2, 8, 4, 3, 7, 1, 5, 6}
# exit
# End time: 03:01:14 on Mar 31,2022, Elapsed time: 0:00:01
# Errors: 0, Warnings: 0
Done
(3)縮位
縮位操作(sum, product, and, or, xor)是有返回值的,因此可以賦值給另一個int型變數
檢視程式碼
module array_reduction;
int array[8]='{1,2,3,4,5,6,7,8};
int res;
initial begin
res= array.sum;
$display("sum: %0d",res);
res= array.product;
$display("product: %0d",res);
res= array.and;
$display("and: 0x%0h",res);
res= array.or;
$display("or: 0x%0h",res);
res= array.xor;
$display("and: 0x%0h",res);
end
endmodule
編譯結果
# Loading sv_std.std
# Loading work.array_reduction(fast)
#
# vsim -voptargs=+acc=npr
# run -all
# sum: 36
# product: 40320
# and: 0x0
# or: 0xf
# and: 0x8
# exit
# End time: 03:15:41 on Mar 31,2022, Elapsed time: 0:00:00
# Errors: 0, Warnings: 0
Done