]> icculus.org git repositories - icculus/xz.git/blob - debug/hex2bin.c
Put the interesting parts of XZ Utils into the public domain.
[icculus/xz.git] / debug / hex2bin.c
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       hex2bin.c
4 /// \brief      Converts hexadecimal input strings to binary
5 //
6 //  Author:     Lasse Collin
7 //
8 //  This file has been put into the public domain.
9 //  You can do whatever you want with this file.
10 //
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #include "sysdefs.h"
14 #include <stdio.h>
15 #include <ctype.h>
16
17
18 static int
19 getbin(int x)
20 {
21         if (x >= '0' && x <= '9')
22                 return x - '0';
23
24         if (x >= 'A' && x <= 'F')
25                 return x - 'A' + 10;
26
27         return x - 'a' + 10;
28 }
29
30
31 int
32 main(void)
33 {
34         while (true) {
35                 int byte = getchar();
36                 if (byte == EOF)
37                         return 0;
38                 if (!isxdigit(byte))
39                         continue;
40
41                 const int digit = getchar();
42                 if (digit == EOF || !isxdigit(digit)) {
43                         fprintf(stderr, "Invalid input\n");
44                         return 1;
45                 }
46
47                 byte = (getbin(byte) << 4) | getbin(digit);
48                 if (putchar(byte) == EOF) {
49                         perror(NULL);
50                         return 1;
51                 }
52         }
53 }