1.计算 hex 文件大小
unsigned long calculate_file_size(FILE *pFile){
unsigned long fsize;
fseek(pFile, 0, SEEK_END);
fsize=ftell(pFile);
fseek(pFile, 0, SEEK_SET);
fsize = fsize/2; //两个字符一个字节
return fsize;
}
2.将 hex 文件转换成 byte 数组
void Hex_to_ByteArray(FILE *pFile,char *buffer){
unsigned long i=0;
char ch[3];
while( fgets(ch, 3, pFile) != NULL ) {
int val = strtol(ch, NULL, 16);
buffer[i++] = val;
}
}
3.生成 byte 数组
void ByteArray(FILE *pPile, unsigned long fsize){
char buffer[fsize];
Hex_to_ByteArray(pPile,buffer);
}
4.打开文件调用函数
#include <cstdio>
#include <fcntl.h>
#include <cstdlib>
#include <unistd.h>
void main(){
unsigned long fsize;
FILE *pFile = NULL;
pFile = fopen("/路径/file.hex", "r");
if(pFile == NULL) printf("Can not open file");
fsize = calculate_file_size(pFile);
ByteArray(pPile, fsize);
}