How do I find out the size of a variable or a struct


If I have a structure like this

typedef struct {
  logic valid;
  logic [7:0] addr;
  logic [15:0] tag;
} sample_type_t

how do I determine the number of bits needed to hold this structure


The $bits() system function returns the number of bits required to hold an expression or variable. In the example below it is used to get the bitstream size of a struct and an array.

One big advantage of the $bits() function is that it can be used as an elaboration time constant . Hence, it can be used in the declaration of other data types or variables.

For example:

logic [7:0] fa[10];
typedef struct {
    logic valid;
    bit [7:0] data;
} MyType;
logic [$bits(MyType)-1 : 0] mytype_bitstream;
logic [$bits(fa)-1 : 0] fa_bitstream;

initial begin
    $display("Bitstream size of MyType: %0d", $bits(MyType));
    $display("Bitstream size of Fixed Array: %0d", $size(fa_bitstream));


# Bitstream size of MyType: 9
# Bitstream size of Fixed Array: 80