| 1 | /**/ |
| 2 | |
| 3 | #include <stdio.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <assert.h> |
| 6 | #include <sysexits.h> |
| 7 | |
| 8 | #include "hex.h" |
| 9 | |
| 10 | const char *tohex(uint8 *data, int len, char *buf) { |
| 11 | char *p; |
| 12 | |
| 13 | for (p= buf; |
| 14 | len>0; |
| 15 | len--, data++, p+=2) |
| 16 | sprintf(p,"%02x",*data); |
| 17 | return buf; |
| 18 | } |
| 19 | |
| 20 | void unhex(const char *what, const char *txt, uint8 *datar, int *lenr, |
| 21 | int minlen, int maxlen) { |
| 22 | int l, v; |
| 23 | char buf[3], *ep; |
| 24 | |
| 25 | l= strlen(txt); |
| 26 | if (l%1) { fprintf(stderr,"odd number of hex digits in %s\n",what); exit(EX_DATAERR); } |
| 27 | l>>=1; |
| 28 | if (l<minlen) { fprintf(stderr,"too few hex digits in %s\n",what); exit(EX_DATAERR); } |
| 29 | if (l>maxlen) { fprintf(stderr,"too many hex digits in %s\n",what); exit(EX_DATAERR); } |
| 30 | |
| 31 | if (lenr) *lenr= l; |
| 32 | while (l) { |
| 33 | buf[0]= *txt++; |
| 34 | buf[1]= *txt++; |
| 35 | buf[2]= 0; |
| 36 | v= strtoul(buf,&ep,16); |
| 37 | if (*ep) { fprintf(stderr,"not hex digit in %s: %c\n",what,*ep); exit(EX_DATAERR); } |
| 38 | *datar++= v; |
| 39 | l--; |
| 40 | } |
| 41 | } |