SystemVerilog Casting


#1

Static Casting (Synthesizeable)

The casting happens at compile time. So there is no error checking to see if the result is a legal value. Use this in design or test bench

Format
<type>'(<expression or variable>)

Examples

// Sign casting
a = signed'(x);
a = unsigned'(y);

// Size casting
int unsigned num;
logic  [7:0] a;
a = 8'(num); // Reduce integer (32b) to 8b

// type casting
a = const'(x);
a = some_enum_e'(int_var);

Dynamic Casting (Non-synthesizeable)

Casting happens at run-time. If the casting is invalid, an error is reported.

Format
$cast(dest_var, source_expression_or_var);

Examples

typedef enum {Peter, John, Mary} students_e;
students_e std;

if (!$cast(std, 5+8)) // 13: Invalid cast, results in error
  $display("Cast error");