#include #include #include /******************************************************************* // CATEGORY: File // FUNCTION: CreateHexFile // MODIFIED: 2025.9.28 // USAGE: int = CreateHexFile(*char FileName, *char HexString) // BRIEF: Creates a binary file and writes some bytes into it // // This function creates a binary file and writes bytes into it. // The function expects two string pointers, the first one pointing // to a file name and the second one pointing to a string containing // hexadecimal numbers. The function converts each hexadecimal // digit pair into a byte and writes the bytes to a file. // Non-hexadecimal digits in the arguments are ignored. // // If the file already exists, it will be deleted and replaced // with the new content. The function returns 1 on success or // zero if something went wrong. // // Note: Part of the original HexString will be overwritten with the // binary content, so this function destroys the second argument. // // Usage: int = CreateHexFile(char *FileName, char *HexString) */ int CreateHexFile(char *FileName, char *HexString) { /* This lookup table helps us convert hexadecimal digits to integers quickly */ char *LUT = "ABCDEFGHIJ.......KLMNOPQ.........................KLMNOPQ"; char c, hi, odd = 0; int i = 0, j = 0; FILE *f; if ((f = fopen(FileName, "wb")) == NULL) { fprintf(stderr, "Error: Cannot create file.\n"); return 0; } while ((c = HexString[i++]) != 0) { if (c < 48 || c > 102) continue; /* Non-hex char */ if ((c = LUT[c - 48]) < 65) continue; /* Non-hex char */ c -= 65; /* hex digit is now converted to an integer */ if ((odd = !odd) != 0) hi = c << 4; else HexString[j++] = hi | c; } /* Save last digit if there are odd number of hex digits */ if (odd) HexString[j++] = hi; /* Write converted binary data to file */ fwrite(HexString, j, 1, f); fclose(f); return 1; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void main() { int i; char CharTable[513]; char *ptr = CharTable; /* Create a list of hexadecimal numbers from 00 to FF */ for (i = 0; i < 256; i++, ptr += 2) sprintf(ptr, "%.2X", i); CharTable[513] = 0; mkdir("C:\\TEMP"); CreateHexFile("C:\\TEMP\\ASCII.BIN", CharTable); }