python二机制文件解析
参考连接:https://blog.csdn.net/lovelyaiq/article/details/81988185
C语言解析:
#include "stdlib.h" #include "stdio.h" typedef unsigned int uint32_t; typedef unsigned char uint8_t; #define LESSON_INTERVAL_TRAIN_NUM 30 typedef enum { SPORT_SEGMENT_WARM_UP = 0, SPORT_SEGMENT_TRAIN, SPORT_SEGMENT_REST, SPORT_SEGMENT_RELAX }SPORT_SEGMENT_TYPE_E; typedef struct sport_segment_cell { SPORT_SEGMENT_TYPE_E type; uint32_t start_timestamp; }sport_segment_cell_t; typedef struct sport_segment { uint8_t seg_max; sport_segment_cell_t seg[LESSON_INTERVAL_TRAIN_NUM]; }sport_segment_t; typedef struct core_segment { uint32_t crc32; sport_segment_t data; }core_segment; int file_parse(const char* file_name) { int size = 0; core_segment seg = {0}; FILE *fp = fopen(file_name, "rb"); if(NULL == fp) { printf("file::%s open failed\n", file_name); return -1; } size = fread(&seg, 1, sizeof(core_segment), fp); printf("size==%d, src ==%d\n", size, sizeof(core_segment)); #if 1 if(sizeof(core_segment) != size) { printf("read file failed size==%d\n", size); fclose(fp); return -1; } #endif printf("crc32==%lu\n", seg.crc32); printf("seg max==%d\n", seg.data.seg_max); for(int i = 0; i < seg.data.seg_max; i++) { printf("info [%d, %ld]\n", seg.data.seg[i].type, seg.data.seg[i].start_timestamp); } fclose(fp); //printf("core segment size==%d\n", sizeof(core_segment)); } int main(int argc, char const *argv[]) { printf("%d\n", argc); for(int i = 0; i < argc; i++) { printf("%d,%s\n", i, argv[i]); } if(argc >= 2) { file_parse(argv[1]); } return 0; }
对应的 python 代码如下:
import sys import struct import os def file_pase(file_name): print('file_name==', file_name) try: f_src = open(file_name, 'rb') contents = f_src.read() offset = 0 print(len(contents)) #data = struct.unpack('62i', contents) data = struct.unpack_from('2I', contents, offset) print('data==', data) #''' #print(data[0],data[1]) offset += 8 max = data[1] for index in range(max): data = struct.unpack_from('2I', contents, offset) print(data[0],data[1]) offset += 8 #''' f_src.close() except ValueError as e: print('error:',e) pass if __name__ == '__main__': print('Hello World! ', sys.argv) for i in sys.argv: #print(i) if '.seg' in i: file_pase(i)