File: hex2bin.c

package info (click to toggle)
hping2 2.rc3-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 756 kB
  • ctags: 951
  • sloc: ansic: 6,706; makefile: 110; sh: 83
file content (63 lines) | stat: -rw-r--r-- 931 bytes parent folder | download | duplicates (4)
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
/*
 * hex2bin - simple hex to bin filter
 * antirez@invece.org - under GPL version 2
 */

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int hex2bin(void)
{
	char hex[3];
	int d = 0;
	unsigned char c;
	int stdin_fd = fileno(stdin);
	int n_read;

	while((n_read = read(stdin_fd, hex, 2)) > 0)
	{
		if (n_read == 1)
		{
			if (hex[0] != '\n')
			{
				fprintf(stderr,
				"input parse error, odd digits in hex file\n");
				exit(1);
			}
			else
				exit(1);
		}
		hex[2] = '\0';
		sscanf(hex, "%x", &d);
		c = (unsigned char) d;
		printf("%c", c);
	}
	return 0;
}

int bin2hex(void)
{
	int stdin_fd = fileno(stdin);
	int n_read;
	unsigned char c;

	while((n_read = read(stdin_fd, &c, 1)) > 0)
	{
		printf("%.2x", c);
	}
	return 0;
}

int main(int argc, char **argv)
{
	if (argc >= 2 && strstr(argv[1], "-r"))
		bin2hex();
	else
		hex2bin();

	return 0;
}