systemverilog中关于枚举的用法
在最近的项目中用到了很多次枚举类型,在这里总结一下sv 中的枚举用法.
枚举类型定义了一组具有名称的整数值,在没有指定类型时默认是 int 类型.枚举变量的值只能从这一系列值中选取,通常第一个值会赋给对应的整数值0,后面的值依次递增,如下面的例子Red对应0,yello和green对应1和2 :
enum {RED, YELLOW, GREEN} light_1;// int type; RED = 0, YELLOW = 1, GREEN = 2
enum bit[1:0] {RED, YELLOW, GREEN} light_2; // bit type; RED = 0, YELLOW = 1, GREEN = 2
如果没有给枚举元素赋整数值,如上面就会给元素依次赋值为0、1、2....;如果只有某几个元素没有赋值,则会根据该元素前面的值加1给这个元素赋值,但是要注意两个元素的值不能相同,否则会报错. 此外,枚举元素的值不能以数字开头!
enum {RED=3, YELLOW, GREEN} light_3; // RED = 3, YELLOW = 4, GREEN = 5
enum {RED = 4, YELLOW = 9, GREEN} light_4; // RED = 4, YELLOW = 9, GREEN = 10
enum {RED = 2, YELLOW, GREEN = 3} light_5; // Error : 会出现两个3
enum bit[0:0] {RED, YELLOW, GREEN} light_6; // Error: 至少需要2bit
enum {1WAY, 2TIMES, SIXPACK=6} e_formula; // 元素值错误!
通常使用 typedef 和 enum 来定义枚举类型变量,如下例子:
module tb;
// "e_true_false" is a new data-type with two valid values: TRUE and FALSE
typedef enum {TRUE, FALSE} e_true_false; //typedef 定义枚举类型
initial begin
// Declare a variable of type "e_true_false" that can store TRUE or FALSE
e_true_false answer; //创建枚举对象
// Assign TRUE/FALSE to the enumerated variable
answer = TRUE;//给枚举对象赋值
// Display string value of the variable
$display ("answer = %s", answer.name);//打印枚举使用 %s,如果打印枚举值使用 %d
end
endmodule

注意,虽然枚举类型的每个元素代表一个整数,但是不能直接将范围之外的整数直接赋给枚举变量,这样会报错!
typedef enum bit [1:0] {RED, YELLOW, GREEN} e_light;
module tb;
e_light light;
initial begin
light = GREEN;
$display ("light = %s", light.name());
// 将合理的整数值赋给
light = 0;
$display ("light = %s", light.name());
// OK when explicitly cast
light = e_light'(2);//显示转换是允许的
$display ("light = %s", light.name());
// OK. light is auto-cast to integer
if (light == RED | light == 2)
$display ("light is now %s", light.name());
end
endmodule

下面是枚举常用的方法:

// GREEN = 0, YELLOW = 1, RED = 2, BLUE = 3
typedef enum {GREEN, YELLOW, RED, BLUE} colors;
module tb;
initial begin
colors color;
// Assign current value of color to YELLOW
color = YELLOW;
$display ("color.first() = %0d", color.first()); // First value is GREEN = 0
$display ("color.last() = %0d", color.last()); // Last value is BLUE = 3
$display ("color.next() = %0d", color.next()); // Next value is RED = 2
$display ("color.prev() = %0d", color.prev()); // Previous value is GREEN = 0
$display ("color.num() = %0d", color.num()); // Total number of enum = 4
$display ("color.name() = %s" , color.name()); // Name of the current enum
end
endmodule

浙公网安备 33010602011771号