写一个bin转hex文件的c代码
时间: 2023-05-27 19:01:39 浏览: 186
以下是一个简单的bin转hex文件的c代码,可以将指定的二进制文件转换为对应的Intel HEX格式的文本文件:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *fp_in, *fp_out;
int ch, byte_count, addr_hi, addr_lo, record_type, sum, i;
unsigned char data[16];
long int address = 0;
if (argc != 3) {
printf("Usage: bin2hex input_file output_file\n");
exit(1);
}
if ((fp_in = fopen(argv[1], "rb")) == NULL) {
printf("Error: can't open input file %s.\n", argv[1]);
exit(1);
}
if ((fp_out = fopen(argv[2], "w")) == NULL) {
printf("Error: can't create output file %s.\n", argv[2]);
exit(1);
}
while ((ch = fgetc(fp_in)) != EOF) {
byte_count = 1;
addr_hi = (address >> 8) & 0xFF;
addr_lo = address & 0xFF;
record_type = 0;
data[0] = ch;
while ((ch = fgetc(fp_in)) != EOF && byte_count < 16) {
data[byte_count] = ch;
byte_count++;
}
sum = byte_count + addr_hi + addr_lo + record_type + data[0];
fprintf(fp_out, ":%02X%02X%02X%02X", byte_count, addr_hi, addr_lo, record_type);
for (i = 0; i < byte_count; i++) {
fprintf(fp_out, "%02X", data[i]);
sum += data[i];
}
fprintf(fp_out, "%02X\n", (-sum) & 0xFF);
address += byte_count;
}
fprintf(fp_out, ":00000001FF\n");
fclose(fp_in);
fclose(fp_out);
printf("Conversion finished.\n");
return 0;
}
```
使用方法:编译并执行可执行文件,将需要转换的二进制文件作为第一个参数传入,将转换后的文本文件保存为第二个参数指定的文件中。例如:```bin2hex input.bin output.hex```
阅读全文