Thursday, October 25, 2007

Casting Strings to Enums in SystemVerilog

Every once and awhile, I want to convert a string to an enumeration in SystemVerilog. Casting from strings to enums is not supported in SystemVerilog, but luckily, it is possible to implement a function to do the appropriate conversion using built in methods designed for iterating over the enum values:

class cmd;
// My enumerated type
typedef enum {UNKNOWN, ADD, SUB, MULT} cmd_e;

// Store the string -> enumerated type mappings.
static cmd_e enum_map[string];

// Configure the mapping from string to enum the first
// time this data structure is created.
virtual function void config_enum_map();
cmd_e e;

string str;
e = e.first();
str =;
enum_map[str] = e;

// Note - we’ve already processed the first element above. This loop
// starts at the *second* element.
for (int i = 1; i < e.num(); i++) begin
e =;
str =;
enum_map[str] = e;

foreach (enum_map[m]) begin
$display(”enum_map[%5s] = %5s (%1d)”, m, enum_map[m].name(), enum_map[m]);

endfunction: config_enum_map

function cmd_e get_enum(string s);
get_enum = enum_map[s];

function new();
if (enum_map.num() == 0) begin
endfunction: new

endclass: cmd

program test;
initial begin
cmd c = new;
cmd::cmd_e ce;

string s = “ADD”;
ce = c.get_enum(s);
$display(”Enum = %s (%1d) for string %s”,, ce, s);



In VCS, run the above code using ‘vcsi -sverilog -ntb_opts dtm -R’ to see the following output:

Compiler version VCSi Y-2006.06-SP1; Runtime version VCSi Y-2006.06-SP1;  Oct 21 14:43 2007

enum_map[ADD] = ADD (1)
enum_map[MULT] = MULT (3)
enum_map[SUB] = SUB (2)
enum_map[UNKNOWN] = UNKNOWN (0)
Enum = ADD (1) for string ADD
V C S S i m u l a t i o n R e p o r t

1 comment:

Anonymous said...

Virtual memory is something that I seemingly will never have enough of. It feels like megabytes and gigabytes have become a permanent part of my every day existence. Ever since I bought a Micro SD Card for my Nintendo DS flash card, I've been constantly vigilant for high memory at low prices. I feel like I'm going insane.

(Posted from Nintendo DS running [url=]R4i DSi[/url] Net10)