In Verilog, conversion functions are used to convert data between different formats, specifically between integers, real numbers, and bit representations. These functions facilitate the manipulation and representation of data types within a simulation environment.
$rtoi
Converts a real number to an integer. This function is used when you want to truncate the fractional part of a real number and obtain its integer representation.
integer $rtoi(real_val); // For example, 192.15 becomes 192
$itor
Converts an integer to a real number. This function is used when you want to perform calculations involving real numbers but start with an integer value.
real $itor(int_val); // For example, 192 becomes 192.0
$realtobits
Converts a real number to its binary (bit) equivalent. This function is helpful when you need to represent floating-point values in binary form for storage or transmission.
[63:0] $realtobits(real_val);
$bitstoreal
Converts a bit pattern (binary representation) to a real number. This function is useful when you need to interpret a binary value as a floating-point number.
real $bitstoreal(bit_val);
Example
module conversion_example;
reg [64:0] bit_pattern; // 32-bit binary representation
real real_value;
integer int_value;
initial begin
// Example bit pattern
bit_pattern = 64'h4055480000000000; // Represents 85.125 in IEEE 754 double precision format
// Convert bit pattern to real
real_value = $bitstoreal(bit_pattern);
$display("Bit Pattern to Real: %f", real_value); // Outputs: Bit Pattern to Real: 5.000000
// Convert integer to real
int_value = 10;
real_value = $itor(int_value);
$display("Integer to Real: %f", real_value); // Outputs: Integer to Real: 10.000000
// Convert real to bits
bit_pattern = $realtobits(real_value);
$display("Real to Bit Pattern: 0x%0h", bit_pattern); // Outputs the bit pattern corresponding to 10.0
// Convert real to integer
real_value = 7.5;
int_value = $rtoi(real_value);
$display("Real to Integer: %d", int_value); // Outputs: Real to Integer: 7
end
endmodule
xcelium> run Bit Pattern to Real: 85.125000 Integer to Real: 10.000000 Real to Bit Pattern: 0x4055480000000000 Real to Integer: 7 xmsim: *W,RNQUIE: Simulation is complete.
ASCII <-> Number Conversions
There are several functions and methods available in SystemVerilog for converting strings to numbers and vice versa, particularly focusing on ASCII representations like atoi(), itoa(), atohex(), hextoa() and more.
These built-in functions belong to the string data type in SystemVerilog and are not available in Verilog.
Click here to learn about SystemVerilog Strings !