You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将SystemVerilog 64位打包结构体转换为C/C++位域结构体的方法

实现方案:Python脚本转换SystemVerilog打包结构体到C/C++位域结构体

核心转换逻辑

SystemVerilog的64位打包结构体是从MSB到LSB顺序定义(如示例中my_field_1对应63位,为最高位),而C/C++位域默认按**先定义的成员占低位(LSB)**排列,因此需要将SV字段按位地址从小到大(0到63)反转顺序,同时计算每个字段的位宽。

Python脚本实现

import re
import sys

def convert_sv_struct_to_c(input_file, output_file):
    with open(input_file, 'r') as f:
        content = f.read()
    
    # 匹配结构体名称与内容
    struct_match = re.search(r'typedef struct packed \{\s*(.*?)\s*\} (\w+);', content, re.DOTALL)
    if not struct_match:
        print("错误:未找到合法的SystemVerilog打包结构体")
        return
    
    struct_body = struct_match.group(1)
    struct_name = struct_match.group(2)
    
    # 匹配每个字段:提取位范围与字段名
    field_pattern = re.compile(r'logic\s+\[(\d+):(\d+)\]\s+(\w+);')
    fields = []
    
    for match in field_pattern.finditer(struct_body):
        high_bit = int(match.group(1))
        low_bit = int(match.group(2))
        field_name = match.group(3)
        bit_width = abs(high_bit - low_bit) + 1
        # 记录字段的最低位(用于排序)、名称、位宽
        fields.append( (min(high_bit, low_bit), field_name, bit_width) )
    
    # 按最低位从小到大排序(对应C结构体从LSB到MSB的顺序)
    fields.sort(key=lambda x: x[0])
    
    # 生成C结构体代码
    c_content = f"#include <stdint.h>\n\nstruct {struct_name} {{\n"
    for low_bit, field_name, bit_width in fields:
        c_content += f"    uint64_t {field_name}:{bit_width}; // 对应SV位[{low_bit + bit_width -1}:{low_bit}]\n"
    
    c_content += "};\n"
    
    with open(output_file, 'w') as f:
        f.write(c_content)
    
    print(f"转换完成,输出文件:{output_file}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("使用方法:python sv2c_struct.py <输入SV文件路径> <输出C头文件路径>")
        sys.exit(1)
    convert_sv_struct_to_c(sys.argv[1], sys.argv[2])

使用步骤

  1. 将上述代码保存为sv2c_struct.py
  2. 执行命令:
    python sv2c_struct.py your_sv_file.sv output_struct.h
    

注意事项

  • 脚本仅处理标准格式的SV结构体(typedef struct packed包裹,字段为logic [X:Y] field;形式),若SV文件包含注释、嵌套结构体等特殊语法,需调整正则表达式适配
  • C/C++位域的具体位分配依赖编译器实现,主流编译器(GCC、Clang)行为与示例一致,需确保编译器符合你的位序预期
  • 生成的头文件包含<stdint.h>以支持uint64_t类型,若不需要可手动删除该行

内容的提问来源于stack exchange,提问作者Benny80

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 02:56:21