sv--struct

struct优点

通过struct,我们可以将不同的数据类型元素作为一个整体进行引用,也可以通过名称单独引用。

struct的语法

struct {
[list of variables]
} struct_name;

struct demo

//将三个不同数据类型变更了放在一个结构体种
module tb;
  struct {
  	bit a;
    logic[2:0] b;
    string c;
  } my_test_s;  
endmodule

合并结构体与非合并结构体

默认情况下,结构体是非合并结构体,它具有独立的地址空间,访问需要限定变量名,但避免了名称污染,更加模块化;合并结构体是将所有变量打包成一个整体。在声明时需要采用packed来标注。

代码如下

module tb;
//非合并结构体  
  struct {
  	bit a;
    logic[3:0] b;
    string c;
  } my_test_s;
  
  initial begin
    my_test_s = '{1'b1,4'b1111,"hi"};
    //%p 格式化打印。%x十六进制打印
    $display("my_test_t.a = %p,my_test_t.b = %x,my_test_t.c = %s",
            my_test_s.a,my_test_s.b,my_test_s.c); 
    
    my_test_s.c = "good!";
    
    $display("my_test.c = %s",my_test_s.c);  
    
    $display("my_test = %p",my_test_s);  
    
  end
//合并结构体,大小为4+4,8位
  struct packed{
    bit [3:0] val1;
    logic [3:0] val2; 
  }st_s;
  
  initial begin
    st_s = '{4'ha,4'hb};

    $display("st_s = %p",st_s);  
    
    st_s.val1 = 4'hc;
    $display("st_s.val1 = %h",st_s.val1);  
    
  end
  
endmodule

[运行结果]

my_test_t.a = 1,my_test_t.b = f,my_test_t.c = hi
my_test.c = good!
my_test = '{a:'h1, b:'hf, c:"good!"}
st_s = '{val1:'ha, val2:'hb}
st_s.val1 = c

创建多个结构体变更

module tb;

typedef struct {
  	bit a;
    logic[3:0] b;
    string c;
  } my_test_s;
  
  initial begin
    my_test_s st_s1,st_s2;
    
    st_s1 = '{1'b1,4'b1111,"hi"};
  
    $display("st_s1.a = %p,st_s1.b = %x,st_s1.c = %s",
            st_s1.a,st_s1.b,st_s1.c);     
    st_s1.c = "good!";
    
    $display("st_s1.c = %s",st_s1.c);  
    
    $display("st_s1 = %p",st_s1);  
  end

  
endmodule

[**运行结果**]
```java
st_s1.a = 1,st_s1.b = f,st_s1.c = hi
st_s1.c = good!
st_s1 = '{a:'h1, b:'hf, c:"good!"}

总结

1.struct的定义语法类似C语言,将不同的数据类型放在一起,进行整体引用或者单独引用。
2.默认struct为非合并类型(untagged),需要通过变量名访问成员。合并类型需要加packed关键字。
3.packed struct大小为成员宽度之和,打印时注意宽度匹配。
4.可以用typedef定义struct类型,然后声明多个变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值