把文本格式的HEX文件轉換為二進位文件
#include <Windows.h> //Windows API FindFirstFile #include <iostream>using namespace std;#define BIN_LEN 1024#define BUFF_LEN (3 * BIN_LEN)int main(int argc, char *argv[]){ string strIFileName = argv[1]; WIN32_FIND_DATA wfd; HANDLE hFind = FindFirstFile(argv[1], &wfd); if (INVALID_HANDLE_VALUE == hFind) { return -1; } CloseHandle(hFind); string strOFileName = strIFileName.substr(0, strIFileName.length() - 4) + ".bin"; FILE * pfI, *pfO; fopen_s(&pfI, strIFileName.c_str(), "r"); fopen_s(&pfO, strOFileName.c_str(), "wb"); if (NULL == pfI) { return -2; } if (NULL == pfO) { return -3; } // 字元串轉換處理 char * bufferChar; bufferChar = (char *)malloc(sizeof(char) * BUFF_LEN); char * bufferBin; bufferBin = (char *)malloc(sizeof(char) * BIN_LEN); if (NULL == bufferChar || NULL == bufferBin) { return -4; } size_t readLen = fread(bufferChar, sizeof(char), BUFF_LEN, pfI); int state = 0; char a = 0; while (readLen > 0) { size_t k = 0; for (size_t i = 0; i < readLen; i++) { char c = bufferChar[i]; c = (c >= a && c <= z) ? (c -= (a - A)) : c; //將小寫轉換為大寫 switch (state) { case 0: //狀態0:進入下一個循環 if ((c >= 0&&c <= 9) || (c >= A&&c <= F)) { state = 1; //條件B:讀入字元∈[0-9, a-f, A-F] char m = (c >= A&&c <= F) ? (c - A + 10) : (c - 0); a = m << 4; } break; case 1: //狀態1:當前字元為高位,將其轉為二進位,存入a的高四位中 if ((c >= 0&&c <= 9) || (c >= A&&c <= F)) { // 將低四位存入後寫如二進位文件,最後轉到狀態0 char m = (c >= A&&c <= F) ? (c - A + 10) : (c - 0); a |= (0x11110000 | m); bufferBin[k++] = a; state = 0; a = 0; } else { state = 0; //讀入字元?[0-9, a-f, A-F] a = 0; } break; default: break; } } fwrite(bufferBin, sizeof(char), BIN_LEN, pfO); readLen = fread(bufferChar, sizeof(char), BUFF_LEN, pfI); } fclose(pfI); fclose(pfO); ::MessageBeep(MB_ICONHAND);}
推薦閱讀:
※無比奇妙的3D投影,與峽谷洞穴的完美結合
※去掉這個基因就能長生不老?新研究或可逆轉人腦衰退!
※事物複雜到一定程度就會產生智能,比如地球,這種理論有根據嗎?
※新發現40個基因與人類智力有關;大腦可檢測他人的潛在疾病 | 每周科技播報
※自動化焦慮