comparison libcommon/hexstr.c @ 0:f7145c77b7fb

starting libcommon: factored out of fc-simtool
author Mychaela Falconia <falcon@freecalypso.org>
date Thu, 11 Feb 2021 22:28:45 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f7145c77b7fb
1 /*
2 * This module contains the function for decoding hex strings.
3 */
4
5 #include <sys/types.h>
6 #include <ctype.h>
7 #include <string.h>
8 #include <strings.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 decode_hex_digit(c)
13 {
14 if (c >= '0' && c <= '9')
15 return(c - '0');
16 if (c >= 'A' && c <= 'F')
17 return(c - 'A' + 10);
18 if (c >= 'a' && c <= 'f')
19 return(c - 'a' + 10);
20 return(-1);
21 }
22
23 decode_hex_data_from_string(arg, databuf, minlen, maxlen)
24 char *arg;
25 u_char *databuf;
26 unsigned minlen, maxlen;
27 {
28 unsigned count;
29
30 for (count = 0; ; count++) {
31 while (isspace(*arg))
32 arg++;
33 if (!*arg)
34 break;
35 if (!isxdigit(arg[0]) || !isxdigit(arg[1])) {
36 fprintf(stderr, "error: invalid hex string input\n");
37 return(-1);
38 }
39 if (count >= maxlen) {
40 fprintf(stderr, "error: hex string is too long\n");
41 return(-1);
42 }
43 databuf[count] = (decode_hex_digit(arg[0]) << 4) |
44 decode_hex_digit(arg[1]);
45 arg += 2;
46 }
47 if (count < minlen) {
48 fprintf(stderr, "error: hex string is too short\n");
49 return(-1);
50 }
51 return(count);
52 }