CMake: Bump maximum policy version to 3.27.
[xz.git] / debug / hex2bin.c
blob73246244746ee2fd344f900b08948082693137c6
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.
11 ///////////////////////////////////////////////////////////////////////////////
13 #include "sysdefs.h"
14 #include <stdio.h>
15 #include <ctype.h>
18 static int
19 getbin(int x)
21 if (x >= '0' && x <= '9')
22 return x - '0';
24 if (x >= 'A' && x <= 'F')
25 return x - 'A' + 10;
27 return x - 'a' + 10;
31 int
32 main(void)
34 while (true) {
35 int byte = getchar();
36 if (byte == EOF)
37 return 0;
38 if (!isxdigit(byte))
39 continue;
41 const int digit = getchar();
42 if (digit == EOF || !isxdigit(digit)) {
43 fprintf(stderr, "Invalid input\n");
44 return 1;
47 byte = (getbin(byte) << 4) | getbin(digit);
48 if (putchar(byte) == EOF) {
49 perror(NULL);
50 return 1;