File: hex2bin.c

package info (click to toggle)
xz-utils 5.8.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,612 kB
  • sloc: ansic: 34,454; sh: 6,745; makefile: 938; asm: 303; sed: 39
file content (52 lines) | stat: -rw-r--r-- 902 bytes parent folder | download | duplicates (2)
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
// SPDX-License-Identifier: 0BSD

///////////////////////////////////////////////////////////////////////////////
//
/// \file       hex2bin.c
/// \brief      Converts hexadecimal input strings to binary
//
//  Author:     Lasse Collin
//
///////////////////////////////////////////////////////////////////////////////

#include "sysdefs.h"
#include <stdio.h>
#include <ctype.h>


static int
getbin(int x)
{
	if (x >= '0' && x <= '9')
		return x - '0';

	if (x >= 'A' && x <= 'F')
		return x - 'A' + 10;

	return x - 'a' + 10;
}


int
main(void)
{
	while (true) {
		int byte = getchar();
		if (byte == EOF)
			return 0;
		if (!isxdigit(byte))
			continue;

		const int digit = getchar();
		if (digit == EOF || !isxdigit(digit)) {
			fprintf(stderr, "Invalid input\n");
			return 1;
		}

		byte = (getbin(byte) << 4) | getbin(digit);
		if (putchar(byte) == EOF) {
			perror(NULL);
			return 1;
		}
	}
}