使用python解析二进制文件时,需要了解python与C语言对应的格式,如下:

python解析torrent python解析二进制文件_数据解析


  例如使用C语言保存的二进制格式,结构体为:

struct  Points
{
     int x;
     int y;
     int z;
};
struct Obj_info{
    int id;
    int x1;
    int y1;
    int x2;
    int y2;
    int x3;
    int y3;
    int x4;
    int y4;
    int w;
    int h;
    int vx;
    int vy;
    int vz;
    bool read_flag;
    bool flag_next_frame;
    char current_time[50];
    Points p[200];
};

  Obj_info结构体的字节数为2512,则参数表格,解析的格式为:

fd = open(u"/home/ubuntu/workspace/read_sensor_data/Debug/data/2018_08_22_11_13_50_lidar4.dat", 'rb')
    while fd:
        buf = fd.read(2512)
        if len(buf) == 0:
            break

        id, sensor_type, obs_type, x1, y1, x2, y2, x3, y3, x4, y4, vx, vy, vz = \
            struct.unpack('14i', buf[0:56])
        read_flag, flag_next_frame =  struct.unpack('2B', buf[56:58])
        current_time = str(struct.unpack('50s', buf[58:108]))[3:22]
        OBSPoint = struct.unpack('600i', buf[108:2508])
        point_num = struct.unpack('i', buf[2508:2512])[0]

  则可以将保存到二进制文件中的每个目标数据解析出来。