背景:需要根据一个指定的CRC算法对二进制bin文件进行checksum计算,输出计算结果。
话不多说,上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char u8;
typedef unsigned long int u32;
unsigned long int api_calc_chksum(unsigned char* array,unsigned int len);
u32 GetBinSize(char *filename);
u8 read_bin(char *path, u8 *buf, u32 size);
void write_crc(u32 crc_chksum);
void print_help() {
printf("Usage: CRC_tool.exe --input filename\n");
printf("filename: .bin file name or absolute path of file.\n");
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
print_help();
return 1;
}
else if (strcmp(argv[1], "--input") == 0)
{
unsigned long int crcSum;
unsigned char security_id[4] = {0x4D,0x43,0x55,0x52};
char *edid_data;
unsigned int size=0;
unsigned char* filename = argv[2];
size=GetBinSize(filename);
edid_data = (char *)malloc(size);
//读取bin文件
if(read_bin(filename, edid_data,size)==0)
{
printf("read bin completely!\n");
crcSum = api_calc_chksum(security_id,4);
crcSum += api_calc_chksum(edid_data, size);
printf("CheckSum: %x ",crcSum);
//写入checksum到txt文件
write_crc(crcSum);
return EXIT_SUCCESS;
}
}
else
{
printf("Unknown option: %s\n", argv[1]);
print_help();
}
}
unsigned long int api_calc_chksum(unsigned char* array,unsigned int len)
{
unsigned int i,j;
unsigned long int temp,ret;
unsigned char* ptr;
ret = 0;
ptr = array;
i = len>>2;
temp = 0;
for(j=0;j<i;j++)
{
temp = ptr[0];
temp = temp<<8 | ptr[1];
temp = temp<<8 | ptr[2];
temp = temp<<8 | ptr[3];
ret += temp;
ptr += 4;
}
i = len & 0x03;
temp = 0;
switch(i)
{
case 0:
break;
case 1:
temp = ptr[0];
temp = temp<<24;
break;
case 2:
temp = ptr[0];
temp = temp<<8 | ptr[1];
temp = temp<<16;
break;
case 3:
temp = ptr[0];
temp = temp<<8 | ptr[1];
temp = temp<<8 | ptr[2];
temp = temp<<8;
break;
default:
break;
}
ret += temp;
return ret;
}
u32 GetBinSize(char *filename)
{
u32 siz = 0;
FILE *fp = fopen(filename, "rb");
if (fp)
{
fseek(fp, 0, SEEK_END);
siz = ftell(fp);
fclose(fp);
}
printf("filename=%s,size=%d \n",filename,siz);
return siz;
}
u8 read_bin(char *path, u8 *buf, u32 size)
{
FILE *infile;
if((infile=fopen(path,"rb"))==NULL)
{
printf( "\nCan not open the path: %s \n", path);
perror("Failed to open file");
return 1;
}
fread(buf, sizeof(u8), size, infile);
fclose(infile);
return 0;
}
void write_crc(u32 crc_chksum)
{
// 打开一个文件用于写入
FILE *file = fopen("checksum.txt", "w");
if (file == NULL) {
perror("无法打开文件");
}
// 将数据写入文件
fprintf(file, "%lx\n", crc_chksum);
// 关闭文件
fclose(file);
}
可以通过minGW工具把这个.c文件转成.exe直接运行。
minGW下载:https://blog.youkuaiyun.com/weixin_64064486/article/details/123940266
安装好minGW-后,
gcc test_ok.c -o crc_tool.exe