ch2-Struct

2019-10-24

What is the need to typedef a structure ?

​ Only one variable was created in the example above, but if there’s a need to create multiple structure variables with the same constituents, it’ll be better to create a user defined data type of the structure by typedef. Then st_fruit will become a data-type which can then be used to create variables of that type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module tb;  
// Create a structure called "st_fruit"
// which to store the fruit's name, count and expiry date in days.
// Note: this structure declaration can also be placed outside the module
typedef struct {
string fruit;
int count;
byte expiry;
} st_fruit;

initial begin
// st_fruit is a data type, so we need to declare a variable of this data type
st_fruit fruit1 = '{"apple", 4, 15};
st_fruit fruit2;

// Display the structure variable
$display ("fruit1 = %p fruit2 = %p", fruit1, fruit2);

// Assign one structure variable to another and print
// Note that contents of this variable is copied into the other
fruit2 = fruit1;
$display ("fruit1 = %p fruit2 = %p", fruit1, fruit2);

// Change fruit1 to see if fruit2 is affected
fruit1.fruit = "orange";
$display ("fruit1 = %p fruit2 = %p", fruit1, fruit2);
end
endmodule

Simulation LogClick to try this example in a simulator! img

Packed Structures

A packed structure is a mechanism for subdividing a vector into fields that can be accessed as members and are packed together in memory without gaps. The first member in the structure is the most significant and subsequent members follow in decreasing order of significance.

A structure is declared packed using the packed keyword which by default is unsigned.

看下面注释

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Create a "packed" structure data type which is similar to creating 
// bit [7:0] ctrl_reg;
// ctrl_reg [0] represents en
// ctrl_reg [3:1] represents cfg
// ctrl_reg [7:4] represents mode
typedef struct packed {
bit [3:0] mode;
bit [2:0] cfg;
bit en;
} st_ctrl;

module tb;
st_ctrl ctrl_reg;

initial begin
// Initialize packed structure variable
ctrl_reg = '{4'ha, 3'h5, 1};
$display ("ctrl_reg = %p", ctrl_reg);

// Change packed structure member to something else
ctrl_reg.mode = 4'h3;
$display ("ctrl_reg = %p", ctrl_reg);

// Assign a packed value to the structure variable
ctrl_reg = 8'hfa;
$display ("ctrl_reg = %p", ctrl_reg);
end
endmodule

Simulation Log

1
2
3
4
5
ncsim> run
ctrl_reg = '{mode:'ha, cfg:'h5, en:'h1}
ctrl_reg = '{mode:'h3, cfg:'h5, en:'h1}
ctrl_reg = '{mode:'hf, cfg:'h5, en:'h0}
ncsim: *W,RNQUIE: Simulation is complete.

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!