What is Type Casting? #
Type casting is the process of converting one data type into another. It is especially useful when working with different bit-widths, enum
, struct
, or class
types.
SystemVerilog supports two types of casting:
- Static Casting (done at compile-time)
- Dynamic Casting (done at runtime, especially with classes).
Why Type Casting is Important #
- Prevents mismatched assignments
- Ensures correct data size and interpretation
- Enables class polymorphism
- Helps in hardware modeling (e.g., casting bit-vectors, enums)
1. Static Casting #
Static casting is used to convert values at compile-time between compatible types like enums, bit-vectors, and integers.
Syntax:
<data_type'(expression)
Example:
module static_cast;
int a = 65; // 32-bit integer
byte b; // 8-bit integer
initial begin
b = byte'(a); // Static cast from int to byte
$display("Value of b = %0d", b);
end
endmodule
Output:
Value of b = 65
Explanation: #
a
is anint
(32-bit)b
is abyte
(8-bit)- We convert
a
tobyte
usingbyte'(a)
- Since 65 fits in 8 bits,
b
gets the value 65
2. Dynamic Casting using $cast
#
Dynamic casting is used at runtime, mostly with class handles. It checks if the object types are compatible before casting.
Syntax:
$cast(Destination, Source)
Example: