【问题标题】:How can I automatically scale a $display column width?如何自动缩放 $display 列宽?
【发布时间】:2021-04-17 20:53:53
【问题描述】:

我想$display 列中的字符串,例如固定宽度的表格。 但是,我不知道我的字符串的最大列宽是多少 提前。

假设我有一个 SystemVerilog 字符串数组 (names)。 当我$display他们时,我猜想列(10)的宽度, 但我的猜测太小了:

module tb;

string names [5];

initial begin
    names = '{
        "ALU"           ,
        "COMPARATOR_3"  ,
        "MEMORY"        ,
        "FLOP"          ,
        "ram_macro_with_a_long_name"
    };

    // Display all elements of the array
    foreach (names[i]) begin
        $display("| %10s |", names[i]);
    end
end

endmodule

这是输出:

|        ALU |
| COMPARATOR_3 |
|     MEMORY |
|       FLOP |
| ram_macro_with_a_long_name |

这是我想要的输出:

|                        ALU |
|                 COMPARATOR |
|                     MEMORY |
|                       FLOP |
| ram_macro_with_a_long_name |

我可以猜到一个非常大的数字(比如 100),但它可能要大得多 比我需要的。

如何自动缩放$display 的宽度?

【问题讨论】:

    标签: verilog system-verilog


    【解决方案1】:

    遍历数组计算最大字符串长度 使用len 数组方法。请参阅 IEEE 标准 1800-2017, 第 6.16 节 字符串数据类型。 然后使用$sformatf 创建格式字符串。

    module tb;
    
    string names [5];
    int maxlen = 0;
    string fmt;
    
    initial begin
        names = '{
            "ALU"           ,
            "COMPARATOR"    ,
            "MEMORY"        ,
            "FLOP"          ,
            "ram_macro_with_a_long_name"
        };
    
        // First, lets calculate the maximum string length
        foreach (names[i]) begin
            if (names[i].len() > maxlen) maxlen = names[i].len();
        end
    
        // Create the format which will be used by $display
        //      %%  ... double "%" is needed to create a literal "%"
        //      %0d ... this formats the maxlen number
        //      s   ... string format
        //      |   ... this is just the character I chose for the start/end of the field
        fmt = $sformatf("| %%%0ds |", maxlen);
    
        // Display all elements of the array
        foreach (names[i]) begin
            $display($sformatf(fmt, names[i]));
        end
    end
    
    endmodule
    

    这是输出:

    |                        ALU |
    |                 COMPARATOR |
    |                     MEMORY |
    |                       FLOP |
    | ram_macro_with_a_long_name |
    

    这是edaplayground 上的一个可运行示例。


    上面的输出是右对齐的。要获得左对齐输出,请使用:

    fmt = $sformatf("| %%-%0ds |", maxlen);
    

    输出:

    | ALU                        |
    | COMPARATOR                 |
    | MEMORY                     |
    | FLOP                       |
    | ram_macro_with_a_long_name |
    

    【讨论】:

      猜你喜欢
      • 2021-02-01
      • 2014-07-31
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 2019-11-07
      • 2019-02-24
      相关资源
      最近更新 更多