0% found this document useful (0 votes)
11 views20 pages

arrays_sv_ex

The document provides a comprehensive overview of SystemVerilog, a hardware description and verification language, including practical examples of various digital design components such as a 4-bit adder, D flip-flop, finite state machine, and memory structures. It also covers advanced features like assertions, functional coverage, and different types of arrays (1D, 2D, dynamic, associative, and queues) with corresponding examples. These examples serve as a foundation for understanding and applying SystemVerilog in digital design and verification environments.

Uploaded by

kavyaashree423
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views20 pages

arrays_sv_ex

The document provides a comprehensive overview of SystemVerilog, a hardware description and verification language, including practical examples of various digital design components such as a 4-bit adder, D flip-flop, finite state machine, and memory structures. It also covers advanced features like assertions, functional coverage, and different types of arrays (1D, 2D, dynamic, associative, and queues) with corresponding examples. These examples serve as a foundation for understanding and applying SystemVerilog in digital design and verification environments.

Uploaded by

kavyaashree423
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 20

SystemVerilog is a hardware description and verification language that combines

features of Verilog with new capabilities for advanced verification, object-


oriented programming, and functional coverage. It is widely used in the design and
verification of digital circuits. Below are some practical programs and examples in
SystemVerilog that cover various aspects of digital design and verification:

1. Simple 4-bit Adder (RTL Design)


This example demonstrates a basic 4-bit ripple-carry adder.

module Adder_4bit (
input logic [3:0] A, // 4-bit input A
input logic [3:0] B, // 4-bit input B
input logic Cin, // Carry-in
output logic [3:0] Sum, // 4-bit Sum
output logic Cout // Carry-out
);
always_comb begin
{Cout, Sum} = A + B + Cin;
end
endmodule
2. Testbench for 4-bit Adder
A simple testbench that instantiates the adder and applies test vectors.

module tb_Adder_4bit;
logic [3:0] A, B;
logic Cin, Cout;
logic [3:0] Sum;

// Instantiate the DUT (Device Under Test)


Adder_4bit uut (
.A(A),
.B(B),
.Cin(Cin),
.Sum(Sum),
.Cout(Cout)
);

initial begin
// Apply test vectors
$display("Test Start");
A = 4'b0001; B = 4'b0010; Cin = 0; #10;
$display("A = %b, B = %b, Cin = %b, Sum = %b, Cout = %b", A, B, Cin, Sum,
Cout);

A = 4'b1111; B = 4'b0001; Cin = 1; #10;


$display("A = %b, B = %b, Cin = %b, Sum = %b, Cout = %b", A, B, Cin, Sum,
Cout);

$stop;
end
endmodule
3. D Flip-Flop with Enable
A simple D flip-flop with an enable signal.

module DFF_En (
input logic D, // Data input
input logic clk, // Clock input
input logic en, // Enable input
output logic Q // Output
);
always_ff @(posedge clk) begin
if (en)
Q <= D;
end
endmodule
4. FSM (Finite State Machine)
A simple 2-state FSM design that toggles its state based on an input signal.

module fsm (
input logic clk, // Clock signal
input logic rst, // Reset signal
input logic in, // Input signal
output logic out // Output signal
);
typedef enum logic [1:0] {
S0 = 2'b00,
S1 = 2'b01
} state_t;

state_t state, next_state;

always_ff @(posedge clk or posedge rst) begin


if (rst)
state <= S0;
else
state <= next_state;
end

always_ff @(state or in) begin


case (state)
S0: next_state = in ? S1 : S0;
S1: next_state = in ? S0 : S1;
default: next_state = S0;
endcase
end

always_comb begin
case (state)
S0: out = 0;
S1: out = 1;
default: out = 0;
endcase
end
endmodule
5. Testbench for FSM
A simple testbench for the FSM module.

module tb_fsm;
logic clk, rst, in;
logic out;

// Instantiate the DUT (Device Under Test)


fsm uut (
.clk(clk),
.rst(rst),
.in(in),
.out(out)
);

// Clock generation
always #5 clk = ~clk;

initial begin
// Initialize signals
clk = 0;
rst = 1;
in = 0;

// Reset the FSM


#10 rst = 0;

// Apply test patterns


#10 in = 1; // Trigger state change
#10 in = 0; // Trigger state change
#10 in = 1; // Trigger state change
#10 $stop;
end
endmodule
6. Parameterized Counter (Generic N-bit Counter)
A parameterized counter that can be configured for any width.

module counter #(
parameter WIDTH = 4 // Default to 4-bit counter
)(
input logic clk,
input logic rst,
output logic [WIDTH-1:0] count
);
always_ff @(posedge clk or posedge rst) begin
if (rst)
count <= 0;
else
count <= count + 1;
end
endmodule
7. Assertions Example
Assertions are a key feature in SystemVerilog used for verifying design
correctness. Here’s an example of using an assert statement for checking valid
transitions in a 2-bit counter.

module counter_with_assert (
input logic clk,
input logic rst,
output logic [1:0] count
);
always_ff @(posedge clk or posedge rst) begin
if (rst)
count <= 0;
else
count <= count + 1;
end

// Assert valid counter values (should be in range 0 to 3 for a 2-bit counter)


assert property (count >= 0 && count <= 3)
else $fatal("Counter out of bounds!");
endmodule
8. Functional Coverage Example
This is an example of functional coverage for a simple 2-bit counter. It tracks how
many different states of the counter have been hit during simulation.

class coverage_example;
covergroup counter_cover @(posedge clk);
coverpoint count;
endgroup

counter_cover cvr;

function new();
cvr = new;
endfunction
endclass

module counter_with_coverage (
input logic clk,
input logic rst,
output logic [1:0] count
);
coverage_example cov;

always_ff @(posedge clk or posedge rst) begin


if (rst)
count <= 0;
else
count <= count + 1;
end

initial begin
cov = new();
end
endmodule
9. Random Number Generation
A simple example of generating random numbers using SystemVerilog's randomization
features.

module random_gen (
output logic [7:0] random_val
);
initial begin
// Randomize the value
randomize(random_val);
$display("Random value: %0d", random_val);
end
endmodule
10. Memory Array
A simple memory block design using a 2D array for RAM.
module memory (
input logic [3:0] addr, // Address
input logic [7:0] data_in, // Data input
input logic we, // Write enable
output logic [7:0] data_out // Data output
);
logic [7:0] mem [0:15]; // 16 words of 8 bits

always_ff @(posedge clk) begin


if (we)
mem[addr] <= data_in; // Write to memory
end

always_ff @(posedge clk) begin


data_out <= mem[addr]; // Read from memory
end
endmodule
These examples cover a range of topics including basic RTL design, finite state
machines, memory structures, testbenches, assertions, random number generation, and
functional coverage. They provide a solid foundation for understanding and applying
SystemVerilog in digital design and verification environments.

Here's an example of working with arrays in SystemVerilog, focusing on both 1D and


2D arrays, as well as dynamic arrays.

1. 1D Array Example:
A simple example of a fixed-size 1D array.

module array_example;
logic [7:0] arr [0:3]; // Declare a 1D array with 4 elements (each 8 bits
wide)

initial begin
// Initialize the array elements
arr[0] = 8'hFF;
arr[1] = 8'hA5;
arr[2] = 8'h1F;
arr[3] = 8'h00;

// Print the array elements


$display("arr[0] = %h", arr[0]);
$display("arr[1] = %h", arr[1]);
$display("arr[2] = %h", arr[2]);
$display("arr[3] = %h", arr[3]);
end
endmodule
2. 2D Array Example:
A 2D array representing a matrix of 4 rows and 3 columns.

module array_2d_example;
logic [7:0] matrix [0:3][0:2]; // Declare a 2D array (4 rows, 3 columns)

initial begin
// Initialize the 2D array elements
matrix[0][0] = 8'h1;
matrix[0][1] = 8'h2;
matrix[0][2] = 8'h3;

matrix[1][0] = 8'h4;
matrix[1][1] = 8'h5;
matrix[1][2] = 8'h6;

matrix[2][0] = 8'h7;
matrix[2][1] = 8'h8;
matrix[2][2] = 8'h9;

matrix[3][0] = 8'hA;
matrix[3][1] = 8'hB;
matrix[3][2] = 8'hC;

// Display the 2D array values


$display("matrix[0][0] = %h, matrix[0][1] = %h, matrix[0][2] = %h",
matrix[0][0], matrix[0][1], matrix[0][2]);
$display("matrix[1][0] = %h, matrix[1][1] = %h, matrix[1][2] = %h",
matrix[1][0], matrix[1][1], matrix[1][2]);
$display("matrix[2][0] = %h, matrix[2][1] = %h, matrix[2][2] = %h",
matrix[2][0], matrix[2][1], matrix[2][2]);
$display("matrix[3][0] = %h, matrix[3][1] = %h, matrix[3][2] = %h",
matrix[3][0], matrix[3][1], matrix[3][2]);
end
endmodule
3. Dynamic Array Example:
A dynamic array allows the size to be determined at runtime.

module dynamic_array_example;
logic [7:0] dynamic_array[]; // Declare a dynamic array (size unknown at
compile time)
integer i;

initial begin
// Allocate memory for the dynamic array
dynamic_array = new[5]; // Create an array of size 5

// Initialize the dynamic array


for (i = 0; i < 5; i++) begin
dynamic_array[i] = i * 2;
end

// Print the dynamic array elements


for (i = 0; i < 5; i++) begin
$display("dynamic_array[%0d] = %h", i, dynamic_array[i]);
end

// Reallocate and resize the dynamic array


dynamic_array = new[8]; // Resize the array to 8 elements
dynamic_array[5] = 8'hFF;
dynamic_array[6] = 8'hA5;
dynamic_array[7] = 8'h1F;

// Print the resized dynamic array elements


for (i = 0; i < 8; i++) begin
$display("dynamic_array[%0d] = %h", i, dynamic_array[i]);
end
end
endmodule
4. Associative Array Example:
An associative array uses arbitrary keys (e.g., strings or integers) instead of
numeric indices.

module associative_array_example;
// Declare an associative array with string keys and 8-bit values
typedef logic [7:0] my_data_t;
my_data_t assoc_array[string]; // Key is a string, value is an 8-bit logic

initial begin
// Assign values using string keys
assoc_array["apple"] = 8'hFF;
assoc_array["banana"] = 8'hA5;
assoc_array["cherry"] = 8'h1F;

// Access and print values using string keys


$display("apple = %h", assoc_array["apple"]);
$display("banana = %h", assoc_array["banana"]);
$display("cherry = %h", assoc_array["cherry"]);

// Check if a key exists


if (assoc_array.exists("apple")) begin
$display("Key 'apple' exists with value: %h", assoc_array["apple"]);
end
end
endmodule
5. Queue Example (Dynamic Size, FIFO):
A queue can be dynamically resized and works on a first-in-first-out (FIFO) basis.

module queue_example;
// Declare a queue of 8-bit logic values
logic [7:0] queue[$]; // '$' denotes a dynamic size for the queue

initial begin
// Enqueue some values
queue.push_back(8'h01);
queue.push_back(8'h02);
queue.push_back(8'h03);

// Dequeue and display the values


$display("Dequeue: %h", queue.pop_front()); // Output: 01
$display("Dequeue: %h", queue.pop_front()); // Output: 02
$display("Dequeue: %h", queue.pop_front()); // Output: 03

// Check if the queue is empty


if (queue.size() == 0) begin
$display("The queue is empty.");
end
end
endmodule
Summary:
1D Arrays: Fixed-size arrays with indices.
2D Arrays: Arrays with rows and columns (useful for matrices).
Dynamic Arrays: Arrays whose size can be adjusted at runtime.
Associative Arrays: Arrays that use arbitrary keys (like a dictionary).
Queues: Dynamic FIFO structures.
These examples demonstrate how to create and manipulate different types of arrays
in SystemVerilog for use in digital designs and simulations.

Here are some more practical SystemVerilog examples that utilize arrays and other
features of the language. These examples showcase more advanced use cases, such as
managing memory, working with different types of arrays, and building testbenches.

1. Memory Model Using Arrays


This example shows a simple RAM model using a 2D array. This is a typical
application where you need to create memory blocks in a design.

module memory_model (
input logic [7:0] addr, // 8-bit address input
input logic [7:0] data_in, // Data input for writing
input logic write_enable, // Write enable signal
output logic [7:0] data_out // Data output
);
// Declare a 2D array to simulate a simple RAM (256 bytes)
logic [7:0] ram [0:255]; // 256 8-bit wide memory

always_ff @(posedge write_enable) begin


if (write_enable)
ram[addr] <= data_in; // Write data to memory at specified address
end

assign data_out = ram[addr]; // Read data from memory

endmodule
2. Multi-Dimensional Array with Testbench
This example uses a 3D array to represent a simple 3D memory model, like a volume
of data. It also includes a testbench to test it.

module memory_3d_example;
logic [7:0] memory [0:3][0:3][0:3]; // 3x3x3 memory (3D)

initial begin
// Initialize the 3D array with some values
memory[0][0][0] = 8'h1;
memory[0][0][1] = 8'h2;
memory[0][0][2] = 8'h3;

memory[0][1][0] = 8'h4;
memory[0][1][1] = 8'h5;
memory[0][1][2] = 8'h6;

memory[0][2][0] = 8'h7;
memory[0][2][1] = 8'h8;
memory[0][2][2] = 8'h9;

// Accessing the array


$display("memory[0][0][0] = %h", memory[0][0][0]);
$display("memory[0][1][1] = %h", memory[0][1][1]);
$display("memory[0][2][2] = %h", memory[0][2][2]);
end
endmodule
3. Parameterized Array Example
This example demonstrates the use of parameterized arrays in SystemVerilog, where
the size of the array is determined at compile time.

module param_array #(parameter WIDTH = 4, parameter DEPTH = 8);


logic [WIDTH-1:0] arr [0:DEPTH-1]; // Declare an array of size DEPTH and width
WIDTH

initial begin
// Initialize the array
for (int i = 0; i < DEPTH; i++) begin
arr[i] = i * 2;
end

// Print the array elements


for (int i = 0; i < DEPTH; i++) begin
$display("arr[%0d] = %h", i, arr[i]);
end
end
endmodule
4. Dynamic Array with Push/Pop Operations
A dynamic array is useful when you need to store data that can grow or shrink
during simulation. Here's an example where we dynamically allocate and manipulate
the size of an array.

systemverilog
Copy code
module dynamic_push_pop;
logic [7:0] dynamic_array[]; // Declare a dynamic array of 8-bit values

initial begin
// Allocate space for 4 elements
dynamic_array = new[4];

// Push values into the array


dynamic_array.push_back(8'hA1);
dynamic_array.push_back(8'hB2);
dynamic_array.push_back(8'hC3);
dynamic_array.push_back(8'hD4);

// Pop values from the array


$display("Popped value: %h", dynamic_array.pop_front());
$display("Popped value: %h", dynamic_array.pop_front());

// Push new values into the array


dynamic_array.push_back(8'hE5);
dynamic_array.push_back(8'hF6);

// Display the remaining elements


foreach(dynamic_array[i]) begin
$display("dynamic_array[%0d] = %h", i, dynamic_array[i]);
end
end
endmodule
5. Associative Array with Custom Key Type
This example demonstrates using associative arrays with a custom key type. The keys
are integers, but you could use any other type, including strings or enumerations.

module associative_array_example;
// Declare an associative array with integer keys and 8-bit values
logic [7:0] my_array [int]; // Array indexed by integers

initial begin
// Store values in the associative array
my_array[100] = 8'hAA;
my_array[200] = 8'hBB;
my_array[300] = 8'hCC;

// Access and display the values


$display("my_array[100] = %h", my_array[100]);
$display("my_array[200] = %h", my_array[200]);
$display("my_array[300] = %h", my_array[300]);

// Check if a key exists in the associative array


if (my_array.exists(200)) begin
$display("Key 200 exists with value: %h", my_array[200]);
end
end
endmodule
6. Queue with Size Limit
In this example, we create a queue with a size limit and use it to simulate a
simple FIFO buffer. The queue is dynamically resized, and we handle both enqueue
and dequeue operations.

module queue_with_size_limit;
logic [7:0] fifo_queue[$]; // Declare a queue of 8-bit wide elements
integer max_size = 5;

initial begin
// Enqueue elements
if (fifo_queue.size() < max_size) fifo_queue.push_back(8'h01);
if (fifo_queue.size() < max_size) fifo_queue.push_back(8'h02);
if (fifo_queue.size() < max_size) fifo_queue.push_back(8'h03);

// Dequeue and display elements


$display("Dequeue: %h", fifo_queue.pop_front()); // Output: 01
$display("Dequeue: %h", fifo_queue.pop_front()); // Output: 02

// Enqueue more elements (only if the size limit is not exceeded)


if (fifo_queue.size() < max_size) fifo_queue.push_back(8'h04);
if (fifo_queue.size() < max_size) fifo_queue.push_back(8'h05);

// Print queue contents


foreach (fifo_queue[i]) begin
$display("fifo_queue[%0d] = %h", i, fifo_queue[i]);
end
end
endmodule
7. Functional Coverage with Arrays
In this example, we use functional coverage to track the access of different array
values during simulation. This is often used in verification to ensure that all
parts of the design are exercised during testing.

module functional_coverage_array;
logic [7:0] test_array [0:7]; // Array of 8 elements (8-bit wide)
covergroup cg @(posedge clk);
coverpoint test_array[0]; // Coverage for first element
coverpoint test_array[1]; // Coverage for second element
coverpoint test_array[2]; // Coverage for third element
coverpoint test_array[3]; // Coverage for fourth element
coverpoint test_array[4]; // Coverage for fifth element
coverpoint test_array[5]; // Coverage for sixth element
coverpoint test_array[6]; // Coverage for seventh element
coverpoint test_array[7]; // Coverage for eighth element
endgroup

initial begin
// Initialize the array
for (int i = 0; i < 8; i++) begin
test_array[i] = i;
end

// Simulate access to some array elements


#5 test_array[0] = 8'hFF;
#10 test_array[4] = 8'hAA;
#15 test_array[2] = 8'hBB;

// Print the array values


foreach(test_array[i]) begin
$display("test_array[%0d] = %h", i, test_array[i]);
end
end
endmodule
Summary of Examples:
Memory model with a fixed-size array simulating RAM.
3D arrays for modeling more complex data structures like 3D memory or matrices.
Parameterized arrays allow for flexible array sizes.
Dynamic arrays with push/pop operations to simulate data storage and manipulation.
Associative arrays with custom keys (e.g., integers).
Queues with size limits for FIFO behavior.
Functional coverage for tracking array element access during verification.
These examples show various ways to use arrays in SystemVerilog for practical
applications like memory modeling, dynamic data handling, and coverage-based
verification.

in SystemVerilog that focus on arrays and various array manipulations. These


examples will cover a broader range of use cases, including multi-dimensional
arrays, complex data types, bit-selects, string arrays, and array slicing.

1. Using Bit-select with Arrays


This example demonstrates how to access individual bits in an array using bit-
selects in SystemVerilog.

systemverilog
Copy code
module bit_select_example;
logic [15:0] data [0:3]; // Declare a 1D array of 16-bit data (4 elements)

initial begin
// Initialize the array
data[0] = 16'hABCD;
data[1] = 16'h1234;
data[2] = 16'h5678;
data[3] = 16'h9ABC;

// Access individual bits using bit-selects


$display("data[0][7:0] = %h", data[0][7:0]); // Access lower 8 bits
$display("data[1][15:8] = %h", data[1][15:8]); // Access upper 8 bits
$display("data[2][4] = %b", data[2][4]); // Access bit 4 of the 16-bit
value
$display("data[3][12:9] = %h", data[3][12:9]); // Access bits 12 to 9
end
endmodule
2. Array Slicing
SystemVerilog supports array slicing for extracting portions of an array. Here's an
example of how to slice a 1D array.

systemverilog
Copy code
module array_slicing;
logic [7:0] arr [0:7]; // Declare an 8-element array of 8-bit values

initial begin
// Initialize the array
arr[0] = 8'h01;
arr[1] = 8'h02;
arr[2] = 8'h03;
arr[3] = 8'h04;
arr[4] = 8'h05;
arr[5] = 8'h06;
arr[6] = 8'h07;
arr[7] = 8'h08;

// Array slicing: Get the first 4 elements of the array


logic [7:0] slice [0:3]; // Declare a new slice array
slice = arr[0:3]; // Slice the array from index 0 to 3

// Display the sliced values


foreach (slice[i]) begin
$display("slice[%0d] = %h", i, slice[i]);
end
end
endmodule
3. Array of Structs (Complex Data Types)
SystemVerilog allows you to use structs with arrays to model more complex data
types. Here's an example of an array of structs.

systemverilog
Copy code
module array_of_structs;
// Define a struct for storing 8-bit data and a flag
typedef struct {
logic [7:0] data; // 8-bit data
logic valid; // Validity flag
} data_t;

// Declare an array of structs


data_t arr [0:3];
initial begin
// Initialize the array of structs
arr[0] = data_t'(8'hA1, 1);
arr[1] = data_t'(8'hB2, 0);
arr[2] = data_t'(8'hC3, 1);
arr[3] = data_t'(8'hD4, 0);

// Display the struct data


foreach (arr[i]) begin
$display("arr[%0d].data = %h, arr[%0d].valid = %b", i, arr[i].data, i,
arr[i].valid);
end
end
endmodule
4. String Array Example
This example demonstrates how to use string arrays to store and manipulate string
data.

systemverilog
Copy code
module string_array_example;
string names [0:3]; // Declare a string array with 4 elements

initial begin
// Initialize the string array
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
names[3] = "David";

// Access and display the string array elements


foreach (names[i]) begin
$display("names[%0d] = %s", i, names[i]);
end
end
endmodule
5. Dynamic Arrays with Reallocation
In this example, we demonstrate dynamic arrays where we can reallocate the array at
runtime.

systemverilog
Copy code
module dynamic_array_reallocation;
logic [7:0] dyn_arr[]; // Declare a dynamic array of 8-bit values

initial begin
// Initial allocation of 5 elements
dyn_arr = new[5];

// Initialize the dynamic array


for (int i = 0; i < 5; i++) begin
dyn_arr[i] = 8'hA0 + i;
end

// Print initial array elements


foreach(dyn_arr[i]) begin
$display("dyn_arr[%0d] = %h", i, dyn_arr[i]);
end
// Reallocate the dynamic array to 10 elements
dyn_arr = new[10];

// Initialize the newly allocated array


for (int i = 5; i < 10; i++) begin
dyn_arr[i] = 8'hB0 + i;
end

// Print the reallocated array elements


foreach(dyn_arr[i]) begin
$display("dyn_arr[%0d] = %h", i, dyn_arr[i]);
end
end
endmodule
6. Multidimensional Array with For-Loop
This example demonstrates how to work with a 2D array and manipulate its values
using a for loop.

systemverilog
Copy code
module multidimensional_array;
logic [7:0] matrix [0:2][0:2]; // Declare a 3x3 matrix

initial begin
// Initialize the matrix with values
for (int i = 0; i < 3; i++) begin
for (int j = 0; j < 3; j++) begin
matrix[i][j] = (i + 1) * (j + 1);
end
end

// Print the matrix elements


for (int i = 0; i < 3; i++) begin
for (int j = 0; j < 3; j++) begin
$display("matrix[%0d][%0d] = %h", i, j, matrix[i][j]);
end
end
end
endmodule
7. Array of Queues
An array of queues is useful when you need multiple FIFO buffers. Here's an example
of how to implement it.

module array_of_queues;
// Declare an array of queues, each holding 8-bit values
logic [7:0] queue_array [0:2] [$]; // 3 queues, dynamic size

initial begin
// Initialize and enqueue values to each queue
queue_array[0].push_back(8'h11);
queue_array[0].push_back(8'h22);

queue_array[1].push_back(8'h33);
queue_array[1].push_back(8'h44);

queue_array[2].push_back(8'h55);
queue_array[2].push_back(8'h66);
// Dequeue and print from each queue
$display("Queue 0: %h, %h", queue_array[0].pop_front(),
queue_array[0].pop_front());
$display("Queue 1: %h, %h", queue_array[1].pop_front(),
queue_array[1].pop_front());
$display("Queue 2: %h, %h", queue_array[2].pop_front(),
queue_array[2].pop_front());
end
endmodule
8. Array-Based Testbench with Randomized Data
This example shows how to use randomization with arrays to create test data for
verification purposes.

module array_randomization;
logic [7:0] test_data [0:9]; // Declare an array of 10 elements for random
data

initial begin
// Randomize the array elements
foreach (test_data[i]) begin
test_data[i] = $random;
end

// Display the randomized values


foreach (test_data[i]) begin
$display("test_data[%0d] = %h", i, test_data[i]);
end
end
endmodule
9. Memory with Write and Read Access via Array of Registers
This example demonstrates a memory model with read/write functionality using an
array of registers. The module supports a simple read/write interface.

module memory_read_write;
logic [7:0] memory [0:15]; // Declare 16-byte memory

// Write function
task write(input logic [3:0] addr, input logic [7:0] data_in);
memory[addr] = data_in;
endtask

// Read function
function logic [7:0] read(input logic [3:0] addr);
return memory[addr];
endfunction

initial begin
// Writing to memory
write(4'h0, 8'hAA);
write(4'h1, 8'hBB);
write(4'h2, 8'hCC);

// Reading from memory


$display("memory[0] = %h", read(4'h0));
$display("memory[1] = %h", read(4'h1));
$display("memory[2] = %h", read(4'h2));
end
endmodule
Summary:
These additional examples cover:

Bit-selects for accessing individual bits within arrays.


Array slicing for extracting portions of arrays.
Array of structs for modeling complex data types.
String arrays for handling textual data.
Dynamic arrays with runtime reallocation.
Multidimensional arrays for grid or matrix-like structures.
Arrays of queues for FIFO buffers.
Randomized arrays for generating test data.
Memory models with read/write operations.
These examples showcase how arrays can be effectively used in SystemVerilog to
model complex data structures and manage data flow in simulations.

SystemVerilog offers even more powerful features related to arrays and other types
of collections that I didn't explicitly highlight in the previous examples. Here
are a few additional array-related concepts and operations that may be of interest
and weren't fully covered:

1. Packed Arrays
Packed arrays are arrays where the individual elements are packed together into a
contiguous bitfield. This is useful when you need a compact, contiguous
representation of data (e.g., for hardware registers or signals).

Example: Packed Array (bit-vector)

module packed_array_example;
logic [7:0] packed_arr [0:3]; // A packed array of 8-bit wide values

initial begin
packed_arr[0] = 8'hFF; // Assign 8-bit values
packed_arr[1] = 8'h0F;
packed_arr[2] = 8'hA1;
packed_arr[3] = 8'h5A;

// Access and print values


foreach (packed_arr[i]) begin
$display("packed_arr[%0d] = %h", i, packed_arr[i]);
end
end
endmodule
Packed arrays are generally used for creating more compact data representations
that map directly to the hardware (such as signals in a module or packed
registers).

2. Associative Arrays with Complex Key Types


While associative arrays can have simple types as keys (like integers), they can
also have complex key types, including enum types or structs.

Example: Associative Array with Enum Keys

module associative_array_enum_example;
typedef enum logic [1:0] {
IDLE = 2'b00,
RUNNING = 2'b01,
STOPPED = 2'b10
} state_t;

// Declare an associative array with enum as the key


logic [7:0] state_data [state_t]; // Array indexed by state_t enum

initial begin
// Initialize values for each enum state
state_data[IDLE] = 8'h01;
state_data[RUNNING] = 8'hFF;
state_data[STOPPED] = 8'h00;

// Access and print the values based on the enum keys


$display("state_data[IDLE] = %h", state_data[IDLE]);
$display("state_data[RUNNING] = %h", state_data[RUNNING]);
$display("state_data[STOPPED] = %h", state_data[STOPPED]);
end
endmodule
3. Dynamically Sized Arrays (Without new[])
Sometimes, you may not want to explicitly use the new[] allocation method.
SystemVerilog allows for dynamic sizing of arrays in a slightly different way than
C or other languages.

Example: Dynamically Sized Array

module dynamic_array_no_new;
logic [7:0] arr[]; // Declare a dynamically sized array without explicit
allocation

initial begin
// Initially, the array is empty
$display("Array size initially: %0d", arr.size());

// Assign a value and resize dynamically


arr = '{8'hA1, 8'hB2, 8'hC3}; // Direct assignment with resizing
$display("Array size after assignment: %0d", arr.size());

// Print elements
foreach (arr[i]) begin
$display("arr[%0d] = %h", i, arr[i]);
end
end
endmodule
This example uses direct array assignment, where the array is resized dynamically
based on the size of the assigned values.

4. Array-Based Functions
You can pass arrays to functions, which is useful when encapsulating array-related
logic in reusable functions.

Example: Function with Array Parameter

module array_function_example;
logic [7:0] arr [0:4]; // Declare a 5-element array

// Function to calculate the sum of elements in an array


function automatic logic [7:0] sum_array(input logic [7:0] arr[]);
logic [7:0] sum = 0;
foreach (arr[i]) begin
sum = sum + arr[i];
end
return sum;
endfunction

initial begin
// Initialize the array
arr[0] = 8'h01;
arr[1] = 8'h02;
arr[2] = 8'h03;
arr[3] = 8'h04;
arr[4] = 8'h05;

// Call the function to calculate the sum


logic [7:0] result = sum_array(arr);
$display("Sum of array elements = %h", result);
end
endmodule
This demonstrates how you can create functions that accept arrays as arguments and
process them, such as calculating the sum of the elements.

5. Array Manipulation with foreach and size()


While the foreach loop and size() function were used in previous examples, they can
be extended for more advanced manipulations, like removing elements from arrays
(for dynamic arrays or queues) or iterating with conditions.

Example: Removing Elements from a Dynamic Array

module dynamic_array_remove;
logic [7:0] dyn_arr[]; // Declare a dynamic array

initial begin
// Initialize the array with some values
dyn_arr = new[5];
dyn_arr[0] = 8'hA1;
dyn_arr[1] = 8'hB2;
dyn_arr[2] = 8'hC3;
dyn_arr[3] = 8'hD4;
dyn_arr[4] = 8'hE5;

// Print the array before removing an element


$display("Array before removal:");
foreach (dyn_arr[i]) begin
$display("dyn_arr[%0d] = %h", i, dyn_arr[i]);
end

// Remove the element at index 2 (C3)


dyn_arr.delete(2); // `delete` removes an element from a dynamic array

// Print the array after removal


$display("Array after removal:");
foreach (dyn_arr[i]) begin
$display("dyn_arr[%0d] = %h", i, dyn_arr[i]);
end
end
endmodule
6. Arrays of Arrays (Nested Arrays)
You can also have nested arrays where each element is another array. This can be
useful when you need to represent more complex structures like matrices or tables.

Example: Arrays of Arrays

module nested_array_example;
logic [7:0] table [0:2][0:3]; // Declare a 2D array (3 rows, 4 columns)

initial begin
// Initialize the 2D array with values
table[0] = '{8'h01, 8'h02, 8'h03, 8'h04};
table[1] = '{8'h05, 8'h06, 8'h07, 8'h08};
table[2] = '{8'h09, 8'h0A, 8'h0B, 8'h0C};

// Access and print the values from the 2D array


foreach (table[i, j]) begin
$display("table[%0d][%0d] = %h", i, j, table[i][j]);
end
end
endmodule
7. Array Operations: Sorting and Searching
You can perform various operations like sorting and searching on arrays using
built-in SystemVerilog functions or custom logic.

Example: Sorting an Array

module sort_array_example;
logic [7:0] arr [0:5]; // Declare an array

// Simple Bubble Sort


task bubble_sort(input inout logic [7:0] arr[]);
logic [7:0] temp;
for (int i = 0; i < arr.size() - 1; i++) begin
for (int j = i + 1; j < arr.size(); j++) begin
if (arr[i] > arr[j]) begin
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
end
end
end
endtask

initial begin
// Initialize the array
arr[0] = 8'hA1;
arr[1] = 8'h5B;
arr[2] = 8'h30;
arr[3] = 8'hFF;
arr[4] = 8'h12;
arr[5] = 8'h7A;

// Sort the array


bubble_sort(arr);

// Display the sorted array


foreach (arr[i]) begin
$display("arr[%0d] = %h", i, arr[i]);
end
end
endmodule
8. Array of Strings
You can also work with arrays of strings, which is useful for handling multiple
textual data items.

Example: Array of Strings


systemverilog
Copy code
module array_of_strings;
string str_arr [0:3]; // Declare an array of strings

initial begin
str_arr[0] = "Hello";
str_arr[1] = "SystemVerilog";
str_arr[2] = "Array Operations";
str_arr[3] = "Example";

foreach (str_arr[i]) begin


$display("str_arr[%0d] = %s", i, str_arr[i]);
end
end
endmodule
Summary of Additional Concepts:
Packed arrays for contiguous bitfields.
Complex key types in associative arrays (like enums).
Direct dynamic array sizing (without explicit allocation).
Functions with array parameters for reusable code.
Removing elements from dynamic arrays.
Nested arrays for multi-dimensional structures.
Array operations like sorting and searching.
Arrays of strings for text data manipulation.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy