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