dat2bin.c
1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#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;
}