-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex2bin.cpp
More file actions
47 lines (44 loc) · 1.15 KB
/
hex2bin.cpp
File metadata and controls
47 lines (44 loc) · 1.15 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
#include <iostream>
#include <cassert>
#include <ctype.h>
#include <cstdio>
void readLine(char* line, unsigned char bytes[], int* bytesRead, int* offset) {
int consumed;
int nFields = sscanf(line, "%x:%n", offset, &consumed);
assert(nFields == 1);
line+=consumed;
unsigned int value;
for (*bytesRead = 0; sscanf(line, "%x%n", &value, &consumed) == 1; ++*bytesRead) {
line+=consumed;
bytes[*bytesRead] = (unsigned char)value;
}
for (; *line != 0; ++line) {
if (!isspace(*line)) {
fprintf(stderr, "Parsing error");
exit(-1);
}
}
}
void outputBytes(unsigned char bytes[], int numBytes, int offset) {
for (int i = 0; i < numBytes; ++i) {
fputc(bytes[i], stdout);
}
}
int main(int argc, char* argv[]) {
for (int i = 1; i < argc; ++i) {
FILE* f = fopen(argv[i], "r");
char* line = NULL;
size_t len;
unsigned char bytes[255];
int bytesRead;
int offset;
while (getline(&line, &len, f) != -1) {
readLine(line, bytes, &bytesRead, &offset);
outputBytes(bytes, bytesRead, offset);
free(line);
line = NULL;
}
fclose(f);
}
return 0;
}