]> icculus.org git repositories - icculus/xz.git/blob - debug/hex2bin.c
Various code cleanups the the xz command line tool.
[icculus/xz.git] / debug / hex2bin.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       hex2bin.c
4 /// \brief      Converts hexadecimal input strings to binary
5 //
6 //  This code has been put into the public domain.
7 //
8 //  This library is distributed in the hope that it will be useful,
9 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 //
12 ///////////////////////////////////////////////////////////////////////////////
13
14 #include "sysdefs.h"
15 #include <stdio.h>
16 #include <ctype.h>
17
18
19 static int
20 getbin(int x)
21 {
22         if (x >= '0' && x <= '9')
23                 return x - '0';
24
25         if (x >= 'A' && x <= 'F')
26                 return x - 'A' + 10;
27
28         return x - 'a' + 10;
29 }
30
31
32 int
33 main(void)
34 {
35         while (true) {
36                 int byte = getchar();
37                 if (byte == EOF)
38                         return 0;
39                 if (!isxdigit(byte))
40                         continue;
41
42                 const int digit = getchar();
43                 if (digit == EOF || !isxdigit(digit)) {
44                         fprintf(stderr, "Invalid input\n");
45                         return 1;
46                 }
47
48                 byte = (getbin(byte) << 4) | getbin(digit);
49                 if (putchar(byte) == EOF) {
50                         perror(NULL);
51                         return 1;
52                 }
53         }
54 }