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