Type casting in SystemVerilog
SystemVerilog adds a cast operator ( ' , forward tick) that supports the ability to cast a value to a different type. The expression to be cast should be enclosed in parentheses or within concatenation or replication braces and is self-determined. The syntax is
<casting_type> '(<expression>)
shortint'(2 * 4) // cast result of 2 *4 to shortint
In addition to this, SV also offers support to cast a unsigned value to signed (or vice versa) and to cast a vector to a different size.
<size>'(<expression>)
logic [7:0] x;
x = 8'(5) // cast literal value 5 to 8-bits wide
<sign>'(<expression>)
y = signed'(x)
Static casting does not include run-time checking i.e. if the cast results in a illegal value during run time, SV does not report any error. For more robust checking, SV offers a dynamic cast function $cast that performs dynamic run time checking. The syntax of $cast is
$cast (dest_var, source_exp) where
dest_var is the variable to which assignment is made and
source_exp is expression that is assigned
-
int x, y;
-
always @(posedge clk)
-
$cast(y, 2.5 * x);
$cast can also be defined as a task and reports a error if the cast value is illegal during runtime. An example would be assigning a cast value to an enumerated type that is not in the set. When called as a function, $cast returns a '1' if the cast was successful or a '0' if it fails. When called as a function, $cast does not report any runtime error and leaves the destination variable unchanged.
-
typedef enum { ADD, MUL, DIVI, SUB, MOD } Opcode;
-
Opcode operat_e;
-
$cast( operat_e, 2 + 1 ); // Dynamic cast : assigns 3 => DIVI to operat_e
-
operat_e = Opcode'(2+1) // Static cast
Type casting can also applied to unpacked arrays and structs known as bit-stream casting. We will visit this when we cover arrays and structs.
Sphere: Related Content