Update copyright notices.
[userv-utils] / ipif / hex.c
1 /*
2 * Copyright (C) 1997,2000 Ian Jackson
3 *
4 * This is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with userv-utils; if not, write to the Free Software
16 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <assert.h>
22 #include <sysexits.h>
23
24 #include "hex.h"
25
26 const char *tohex(uint8_t *data, int len, char *buf) {
27 char *p;
28
29 for (p= buf;
30 len>0;
31 len--, data++, p+=2)
32 sprintf(p,"%02x",*data);
33 return buf;
34 }
35
36 void unhex(const char *what, const char *txt, uint8_t *datar, int *lenr,
37 int minlen, int maxlen) {
38 int l, v;
39 char buf[3], *ep;
40
41 l= strlen(txt);
42 if (l%1) { fprintf(stderr,"odd number of hex digits in %s\n",what); exit(EX_DATAERR); }
43 l>>=1;
44 if (l<minlen) { fprintf(stderr,"too few hex digits in %s\n",what); exit(EX_DATAERR); }
45 if (l>maxlen) { fprintf(stderr,"too many hex digits in %s\n",what); exit(EX_DATAERR); }
46
47 if (lenr) *lenr= l;
48 while (l) {
49 buf[0]= *txt++;
50 buf[1]= *txt++;
51 buf[2]= 0;
52 v= strtoul(buf,&ep,16);
53 if (*ep) { fprintf(stderr,"not hex digit in %s: %c\n",what,*ep); exit(EX_DATAERR); }
54 *datar++= v;
55 l--;
56 }
57 }