在单片机程序里面 有时候 要将 bin 转换为 hex 写下 mark 一下
#include "stdio.h"
typedef unsigned char BYTE;
typedef unsigned long DWORD;
int main(int argc, char* argv[])
{
char *pt, buf[256] = ":", filename[256];
BYTE *pRomData;
int i, filelen, addr;
BYTE sum;
FILE *fp;
if (argc < 3)
{
printf("no parameter!");
return 1;
}
for (i = 0; argv[1][i] != '.'; i++) filename[i] = argv[1][i];
filename[i++] = '.'; filename[i++] = 'h'; filename[i++] = 'e'; filename[i++] = 'x'; filename[i++] = 0;
sscanf(argv[2], "%x", &addr);
fp = fopen(argv[1], "rb");
if (fp == NULL)
{
printf("no file!");
return 1;
}
fseek(fp, 0, SEEK_END);
filelen = ftell(fp);
printf("file len:%d\r\n", filelen);
pRomData = new BYTE[filelen];
fseek(fp, 0, SEEK_SET);
fread(pRomData, 1, filelen, fp);
fclose(fp);
fp = fopen(filename, "wb");
pt = buf + 1;
sum = 0x100 - 02 - 04 - (addr / 0x1000000) - ((addr & 0xFF0000) / 0x10000);
pt += sprintf(pt, "02000004%04X%02X\r\n", addr / 0x10000, sum);
fwrite(buf, 1, (DWORD)pt - (DWORD)buf, fp);
for (addr = 0; addr<filelen;)
{
DWORD cnt, i;
pt = buf + 1;
cnt = filelen - addr; if (cnt>0x20) cnt = 0x20; pt += sprintf(pt, "%02X%04X00", cnt, addr); sum = (BYTE)(cnt + (addr / 0x100) + (addr & 0xFF));
for (i = 0; i<cnt; i++)
{
pt += sprintf(pt, "%02X", pRomData[addr]); sum += pRomData[addr];
++addr;
}
sum = 0x100 - sum;
pt += sprintf(pt, "%02X\r\n", sum);
fwrite(buf, 1, (DWORD)pt - (DWORD)buf, fp);
}
pt = buf + 1;
pt += sprintf(pt, "00000001FF\r\n");
fwrite(buf, 1, (DWORD)pt - (DWORD)buf, fp);
fclose(fp);
}
使用方法 bin2hex abc.bin 0x8000000
abc.bin 是文件名 0x8000000 是要放到的地址
编译好的exe 下载地址:https://download.csdn.net/download/ljxh401/11275081