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

使用ASN.1TOOLS解码多记录BER文件仅获单条记录的问题

解决ASN.1TOOLS解码多记录BER文件的问题

你的问题出在asn1_spec.decode()默认仅解码单条ASN.1结构,而你的BER文件包含多条连续的CallDetailRecord编码数据。要处理这种场景,需要循环解码剩余的二进制数据,直到耗尽所有内容。

修改后的代码

import os
import asn1tools
import pandas as pd

# 解码函数:支持单文件多记录
def decode_ber_file(file_path):
    records = []
    with open(file_path, 'rb') as file:
        binary_data = file.read()
        remaining_data = binary_data
        
        while remaining_data:
            try:
                # 启用return_remaining=True,获取解码后的数据和剩余未解码字节
                decoded_data, remaining_data = asn1_spec.decode(
                    'CallDetailRecord', 
                    remaining_data, 
                    return_remaining=True
                )
                # 转换字节串为UTF-8字符串
                decoded_data = {
                    key: value.decode('utf-8') if isinstance(value, bytes) else value 
                    for key, value in decoded_data.items()
                }
                records.append(decoded_data)
            except Exception as e:
                # 记录错误并终止当前文件的解码(可根据需求改为跳过错误继续)
                records.append({"error": f"文件{filename}解码出错: {str(e)}"})
                break
    return records

directory_path = 'msc_binary'
asn1_spec = asn1tools.compile_files('msc_schema.asn', codec='ber')

decoded_records = []

for filename in os.listdir(directory_path):
    if filename.endswith('.ber'):
        file_path = os.path.join(directory_path, filename)
        file_records = decode_ber_file(file_path)
        # 过滤掉错误记录,仅保留有效数据
        valid_records = [rec for rec in file_records if "error" not in rec]
        decoded_records.extend(valid_records)

# 转换为DataFrame
df_msc = pd.DataFrame(decoded_records)

关键说明

  • return_remaining=True参数:这是核心修改,让decode()方法返回两个值——解码完成的单条记录,以及文件中剩余未解码的二进制数据。
  • 循环处理剩余数据:通过while remaining_data循环,持续解码剩余字节,直到文件所有记录处理完毕。
  • 异常处理调整:如果某条记录解码失败,当前文件的解码会终止(可根据需求修改逻辑,比如跳过错误记录继续处理剩余数据)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:17:33