fluffy

Network Archaeology tools for Unix
git clone https://git.woozle.org/neale/fluffy.git

Neale Pickett  ·  2013-01-29

unhex.c

 1/*
 2 * Hex Decoder -- 2012 Zephyr <zephyr@dirtbags.net> This file is in the public domain.  I make no promises about the functionality 
 3 * of this program. 
 4 */
 5
 6#include <stdio.h>
 7
 8int
 9main(int argc, char *argv[])
10{
11	unsigned char acc = 0;
12	unsigned char nybble = 0;
13	unsigned long int count = 0;
14
15	while (1) {
16		int c = getchar();
17
18		count += 1;
19
20		switch (c) {
21			case EOF:
22				return 0;
23			case '0' ... '9':
24				acc = (acc << 4) + c - '0';
25				nybble += 1;
26				break;
27			case 'a' ... 'f':
28				acc = (acc << 4) + c - 'a' + 10;
29				nybble += 1;
30				break;
31			case 'A' ... 'F':
32				acc = (acc << 4) + c - 'A' + 10;
33				nybble += 1;
34				break;
35			default:
36				if (nybble != 0) {
37					fprintf(stderr, "Warning: non-hex character mid-octet at offset %lu\n", count);
38				}
39				break;
40		}
41
42		if (nybble == 2) {
43			putchar(acc);
44			acc = 0;
45			nybble = 0;
46		}
47	}
48
49	return 0;
50}