当前位置: 首页 > 工具软件 > Chex4j > 使用案例 >

bin2cHex

须曜文
2023-12-01
#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 ;

}

 类似资料:

相关阅读

相关文章

相关问答