1 /*
2  *      $Id: hex.c 191 2007-03-30 23:26:38Z boote $
3  */
4 /************************************************************************
5 *									*
6 *			     Copyright (C)  2003			*
7 *				Internet2				*
8 *			     All Rights Reserved			*
9 *									*
10 ************************************************************************/
11 /*
12  *	File:		hex.c
13  *
14  *	Author:		Jeff W. Boote
15  *			Internet2
16  *
17  *	Date:		Tue Dec 16 15:45:00 MST 2003
18  *
19  *	Description:
20  */
21 #include <I2util/utilP.h>
22 #include <ctype.h>
23 
24 /*
25  * buff must be at least (nbytes*2) +1 long or memory will be over-run.
26  */
27 void
I2HexEncode(char * buff,const uint8_t * bytes,size_t nbytes)28 I2HexEncode(
29 	char            *buff,
30 	const uint8_t   *bytes,
31 	size_t          nbytes
32 	)
33 {
34     char    hex[]="0123456789abcdef";
35     size_t  i;
36 
37     for(i=0;i<nbytes;i++){
38         *buff++ = hex[*bytes >> 4];
39         *buff++ = hex[*bytes++ & 0x0f];
40     }
41     *buff = '\0';
42 }
43 
44 /*
45  * Function:	I2HexDecode
46  *
47  * Description:
48  * 	Decode hex chars into bytes. Return True on success, False on error.
49  *
50  * 	It is valid to pass the same memory in for buff and bytes. On
51  * 	input buff should hold the hex encoded string, on output the
52  * 	memory will hold the bytes. (It will take half the memory...)
53  *
54  * In Args:
55  *
56  * Out Args:
57  *
58  * Scope:
59  * Returns:
60  * Side Effect:
61  */
62 I2Boolean
I2HexDecode(const char * buff,uint8_t * bytes,size_t nbytes)63 I2HexDecode(
64         const char  *buff,
65         uint8_t     *bytes,
66         size_t	    nbytes
67         )
68 {
69     char            hex[]="0123456789abcdef";
70     unsigned int    i,j,offset;
71     char            a;
72     uint8_t         byte;
73 
74     for(i=0;i<nbytes;i++,bytes++){
75         byte = 0;
76         for(j=0;(*buff != '\0')&&(j<2);j++,buff++){
77             a = tolower(*buff);
78             for(offset=0;offset<sizeof(hex);offset++){
79                 if(a == hex[offset]){
80                     byte |= offset;
81                     if(!j)
82                         byte <<= 4;
83                     goto byteset;
84                 }
85             }
86             return False;
87 byteset:
88             ;
89         }
90         *bytes = byte;
91     }
92 
93     return True;
94 }
95