dat2bin.c 1.38 KB
#include <stdio.h>
#include <string.h>

inline int char2hex(unsigned char ch)
{
     if (ch >='0' && ch<='9') return (ch - '0');
     if (ch >='A' && ch<='F') return (ch-'A'+10);
     if (ch >='a' && ch<='f') return (ch-'a'+10);

     return -1;
}

int main(int argc, char **argv)
{
    FILE *fdat, *fbin;
    unsigned char sline[256], *start;
    int d1, d2, skip;

    if (argc != 4) {
        printf("\n Usage: dat2bin hex_file binary_file skip");
        printf("\n        Convert hex data file into binary file\n");
        return -1;
    }

    if ((fdat = fopen(argv[1], "rb")) == NULL) {
        printf(" Cannot open file : %s \n", argv[1]);
        return -1; 
    }

    if ((fbin = fopen(argv[2], "wb")) == NULL) {
        printf(" Cannot open file : %s \n", argv[2]);
        fclose(fdat);
        return -1; 
    }
    skip = atoi(argv[3]);
    if (skip < 0) skip = 0;

    while (!feof(fdat)) {
        fgets(sline, sizeof(sline), fdat);
        if (feof(fdat)) break;

        start = strstr(sline+skip, ":");
        if (start == NULL) start = sline+skip;

        while (*start != '\0') {
            d1 = char2hex(*start++);
            if (d1 < 0) continue;

            if (*start == '\0') break;

            d2 = char2hex(*start++);
            if (d2 < 0) fputc(d1, fbin); 
            else fputc((d1<<4) | d2, fbin);
        } 
    }

    fclose(fdat);
	fclose(fbin);
    return 0;
}