有没有办法在系统verilog中将字符串强制转换为枚举?
typedef enum {ABC1,ABC2,ABC3} abc;
program Test ;
abc x1;
string teststring;
initial
begin
teststring="ABC2";
x1=abc'(teststring); // Static cast doesn't work
$display("[%s][%0d]",teststring,x1);
end
endprogram
答案 0 :(得分:2)
施法是按价值而非名称。鉴于您使用的是默认枚举数据类型(int)而未将值分配给任何标识符,ABC1
,ABC2
和ABC3
的值为0
,分别为1
和2
(所有类型为int)。
对此enum
投掷刺痛与将其投射到int
的情况大致相同。 int'("ABC2") == 32'h41424332
并且与任何枚举标识符的值不匹配。
获得所需功能的选项:
创建一个遍历列表并比较名称的函数:
function abc a2e(input string s);
a2e = a2e.first;
repeat(a2e.num) begin
if(a2e.name == s) return a2e;
else a2e = a2e.next;
end
assert(0) else $error("Identifier '%s' not in enum abc",s);
endfunction
有关枚举方法的更多信息:IEEE Std 1800-2012第6.19.5节
关联数组查找:(参见IEEE Std 1800-2012第7.8节和第7.9节)
abc lookup[string];
...
x1 = abc.first;
repeat(x1.num) begin
lookup[x1.name] = x1;
x1 = x1.next;
end
...
teststring="ABC2";
/* Without protection: Non-match creates new entry for with the value
of abc.first (or '{default:???} if specified) and returns the value */
x1 = lookup[teststring];
// With protection
if ( lookup.exists( teststring ))
x1= lookup[teststring];
else
assert(0) else $error("Identifier '%s' not in enum abc",teststring );
如果枚举标识符为1到4个字符,则长值无关紧要,请将名称设为值。 typedef enum {ABC1="ABC1",ABC2="ABC2",ABC3="ABC3"} abc;
要写多久?尝试等效:
typedef enum {ABC[1:3]="ABC1"} abc;
需要更多4个字符?分配数据类型。
typedef enum bit[5*8-1:0] {ABC[10:19]="ABC10", ABC[20:29]="ABC20"} abc;
有关枚举类型范围的更多信息:IEEE Std 1800-2012第6.19.2节
注意:以上是IEEE Std 1800-2005以来的所有功能,必须购买此版本的LRM才能阅读。 2012版本不含IEEE,因此引用此版本。