bin2cHex

#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <wchar.h>

#define BYTES_PER_LINE 0x10


void main(void)
{
	wchar_t binfilename[]=TEXT("d:\\x86.sys");
	char cfilename[]="d:\\1234.h";
	char* buffer=NULL;
	FILE *fp = NULL;
	int numread = 0;
	HANDLE hFile;
	DWORD NumberOfBytesRead=0;


	hFile=CreateFile(binfilename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL ,NULL);
	if ( INVALID_HANDLE_VALUE==hFile)
	{
		printf("打开文件失败\n");
		getchar();
		return;
	}
	numread=GetFileSize(hFile,NULL);
	buffer=new char[numread];
	ZeroMemory(buffer,numread);
	ReadFile(hFile,buffer,numread,&NumberOfBytesRead,NULL);
	CloseHandle(hFile);

	if (NumberOfBytesRead!=numread)
	{
		printf("读取文件失败\n");
		getchar();
		return;
	}



	if ((fp = fopen(cfilename,"wt")) != NULL)
	{
		static char temp[MAX_PATH]  ={0};
		static char temp2[MAX_PATH]  ={0};
		unsigned char *ptr =(unsigned char *) buffer;
		fprintf(fp, "unsigned char firmware[] = {\n");
		for (int i = 0; i < ((numread + BYTES_PER_LINE - 1) / BYTES_PER_LINE); i++)//for not enogh line
		{

			for (int j = 0; j < BYTES_PER_LINE; j++)
			{
				if (((i * BYTES_PER_LINE) + j) < (numread-1))
				{
					sprintf(temp2,"0x%02X, ",*ptr++);
					strcat(temp,temp2);
				}
				else if (((i * BYTES_PER_LINE) + j) < (numread))
				{
					sprintf(temp2,"0x%02X ",*ptr++);
					strcat(temp,temp2);
				}
			}
			fprintf(fp, "%s\n",temp);
			ZeroMemory(temp,MAX_PATH);
		}

		fprintf(fp, "};\n");
		fclose(fp);
	}


	getchar();
	getchar();
	return ;

}

以C++实现程序的名称为chex,符合编码规范,封装成类的形式,调整结构,便于扩展和维护 从命令行参数中读取文件并显示,显示的格式由3种不同的Panel组成。 1,Offset Panel:按16进制显示当前行的起始偏移量 2,Data Panel:以byte为单位,按16进制显示。每行显示8个byte 3,Ascii Panel:显示与Data Panel中对应byte的ascii字符,如果byte为不可显示的,则输出"." 在上述代码基础上接着优化: 1,--panels n,设置Data Panel的个数.n = 1,2,3。默认为1 2,--border mode,设置边框的mode = ascii,mode 默认none。ascii:用字符'+'和'-'来绘制边框。none:不绘制边框。 示例:chex --panels 2 --border ascii test.bin 最后完成如下进阶要求,并给出完整的C++代码: 1,变更参数: --border默认值变更为ascii。 --panels的默认值变更为2。 2,新增参数: --length n,从输入中只读取n个字节显示。 --offset-panel mode offset panel的显示开关,mode = on/off.默认值为on。on:显示offset panel’.off:不显示offset panel。 --ascii-panel mode: ascii panel的显示开关,mode = on/off。默认是为on on。on:显示ascii panel’.off:不显示ascii panel。 例如:chex --offset-panel off --ascii-panel off test.bin --base n 设置数据的进制显示,n = 2,8,10,16 这4种进制,默认为16进制显示 3,新增将其他程序的标准输出,作为chex的输入,例如:echo hello | chex 进阶示例:chex --offset-panel off --ascii-panel off test.bin
最新发布
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值