chiark / gitweb /
upstream changelog: Document merge
[userv-utils.git] / ipif / hex.c
1 /*
2  * This file is part of ipif, part of userv-utils
3  *
4  * Copyright 1996-2013 Ian Jackson <ijackson@chiark.greenend.org.uk>
5  * Copyright 1998 David Damerell <damerell@chiark.greenend.org.uk>
6  * Copyright 1999,2003
7  *    Chancellor Masters and Scholars of the University of Cambridge
8  * Copyright 2010 Tony Finch <fanf@dotat.at>
9  *
10  * This is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with userv-utils; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <assert.h>
27 #include <string.h>
28 #include <sysexits.h>
29
30 #include "hex.h"
31
32 const char *tohex(uint8_t *data, int len, char *buf) {
33   char *p;
34   
35   for (p= buf;
36        len>0;
37        len--, data++, p+=2)
38     sprintf(p,"%02x",*data);
39   return buf;
40 }
41
42 void unhex(const char *what, const char *txt, uint8_t *datar, int *lenr,
43            int minlen, int maxlen) {
44   int l, v;
45   char buf[3], *ep;
46
47   l= strlen(txt);
48   if (l%1) { fprintf(stderr,"odd number of hex digits in %s\n",what); exit(EX_DATAERR); }
49   l>>=1;
50   if (l<minlen) { fprintf(stderr,"too few hex digits in %s\n",what); exit(EX_DATAERR); }
51   if (l>maxlen) { fprintf(stderr,"too many hex digits in %s\n",what); exit(EX_DATAERR); }
52
53   if (lenr) *lenr= l;
54   while (l) {
55     buf[0]= *txt++;
56     buf[1]= *txt++;
57     buf[2]= 0;
58     v= strtoul(buf,&ep,16);
59     if (*ep) { fprintf(stderr,"not hex digit in %s: %c\n",what,*ep); exit(EX_DATAERR); }
60     *datar++= v;
61     l--;
62   }
63 }