-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhex2raw.c
More file actions
120 lines (92 loc) · 2.14 KB
/
hex2raw.c
File metadata and controls
120 lines (92 loc) · 2.14 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
* hex2raw.c
*
* Created on: 03/dec/2012
* Author: Acri Emanuele <crossbower@gmail.com>
*
* Convert hexstrings to raw data (and vice versa).
* Uses stdin and stdout.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "hexstring.h"
#define VERSION "1.5"
#define BUFFER_SIZE 8192
/**
* Convert standard input in hexstring format to raw format
*/
int convert_hexstr_to_raw_loop()
{
char buffer[BUFFER_SIZE];
while (!feof(stdin)) {
/* Read hexstring */
if( !fgets(buffer, BUFFER_SIZE, stdin) ) {
continue;
}
/* Write raw output */
int size = 0;
char *raw = NULL;
raw = hexstr_to_raw(buffer, &size);
fwrite(raw, 1, size, stdout);
fflush(stdout);
free(raw);
}
return 0;
}
/**
* Convert standard input in raw format to hexstring format
*/
int convert_raw_to_hexstr_loop()
{
char buffer[BUFFER_SIZE];
int size;
while (!feof(stdin)) {
/* Read raw */
size = fread(buffer, 1, BUFFER_SIZE, stdin);
/* Write hexstring output */
char *hexstr = raw_to_hexstr(buffer, size);
fprintf(stdout, "%s\n", hexstr);
fflush(stdout);
free(hexstr);
}
return 0;
}
/**
* Usage
*/
void usage(char *progname) {
printf("Hex2Raw " VERSION " [convert hexstrings on stdin to raw data on stdout]\n"
"written by: Emanuele Acri <crossbower@gmail.com>\n\n"
"Usage:\n\t%s [-r|-h]\n\n"
"Options:\n"
"\t-r\treverse mode (raw to hexstring)\n"
"\t-h\tthis help screen\n", progname);
exit(0);
}
/*
* Main function
*/
int main(int argc, char **argv) {
int reverse = 0;
// check arguments
if(argc > 1) {
// raw to hexstring
if(!strcmp(argv[1], "-r")) {
reverse = 1;
}
// unknown options
else {
usage(argv[0]);
}
}
// hexstring to raw data
if(reverse == 0) {
convert_hexstr_to_raw_loop();
}
// raw data to hexstring
else {
convert_raw_to_hexstr_loop();
}
return 0;
}