Built-in Data Types
While Verilog primarily uses reg and wire types, SystemVerilog (SV) introduces the logic type as a more versatile data type.
// SV also provides a corresponding `bit` type.
// Both `logic` and `bit` can be used to create vectors.
// The key difference is:
// `logic` is a 4-state type, representing 0, 1, x (unknown), and z (high-impedance).
// `bit` is a 2-state type, representing only 0 and 1.
Why Introduce 2-State Types?
A primary design goal of SV was to clearly separate the hardware modeling domain from the software programming domain. Two-state types are better suited for modeling high-level software algorithms and testbench components.
- 4-State Types:
integer,logic,reg,net-type(e.g.,wire,tri) - 2-State Types:
byte,shortint,int,longint,bit
Signed vs. Unsigned Classification
- Signed Types:
byte,shortint,int,longint,integer - Unsigned Types:
bit,logic,reg,net-type(e.g.,wire,tri)
Note on Signed Numbers: Negative numbers in signed types are stored in two's complement form. The two's complement of a number is calculated by: 1) inverting all bit (one's complement), and 2) adding 1 to the result.
Example for -127 (assuming an 8-bit representation, most significant bit as sign bit):
Absolute value (127): 0111 1111
One's complement (invert all bits): 1000 0000
Two's complement (add 1): 1000 0001
Thus, -127 is stored as 1000 0001.
With the most significant bit as the sign bit, the codes for +0 (0000 0000) and -0 (1000 0000) would differ. To gain an extra useful value in the signed range, the pattern 1000 0000 is defined to represent -128. This specific value cannot be derived using the standard two's complement calculation from a positive number.
Data Type Conversion in SystemVerilog
SV provides several mechanisms for converting between data types:
-
Static Cast (Explicit): Use a single apostrophe before the type name. The conversion is checked at compile time.
int signed_val = -5; logic [7:0] unsigned_val; unsigned_val = unsigned'(signed_val); // Static cast to unsigned -
Dynamic Cast (Explicit): Use the
$castsystem task. Success or failure is determined at runtime.int src_val; byte target_val; if (!$cast(target_val, src_val)) begin $display("Cast failed!"); end
Both methods above require explicit operators or system functions. Conversions that happen automaticaly during assignments or expressions are called implicit conversions.
Important Implicit Conversion Rule: When a 4-state value containing 'x' or 'z' is implicitly converted to a 2-state type (like bit), these unknown/high-impedance states are converted to 0.
logic [3:0] four_state_data = 4'b111x;
bit [2:0] two_state_data;
two_state_data = four_state_data; // Implicit conversion. Result is 3'b110
// The 'x' bit is treated as 0.
Therefore, when performing operations involving different data types, pay close attention to:
1. Logic State Type (2-state vs. 4-state)
2. Signednesss (signed vs. unsigned)
3. Vector Bit-width