有没有办法在系统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
最佳答案
选角是根据值,而不是名称。假定您使用默认枚举数据类型 (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 的约束,因此引用此版本。
关于enums - 将字符串转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703880/