2 * Worldvisions Weaver Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
5 * Hex encoder and decoder.
11 static inline char tohex(int digit
, char alphabase
)
13 return (digit
< 10 ? '0' : alphabase
) + digit
;
16 static inline int fromhex(char digit
)
21 return digit
- 'A' + 10;
22 return digit
- 'a' + 10;
25 /***** WvHexEncoder *****/
27 WvHexEncoder::WvHexEncoder(bool use_uppercase
)
29 alphabase
= (use_uppercase
? 'A' : 'a') - 10;
34 bool WvHexEncoder::_reset()
40 bool WvHexEncoder::_encode(WvBuf
&in
, WvBuf
&out
, bool flush
)
42 while (in
.used() != 0)
44 unsigned char byte
= in
.getch();
45 out
.putch(tohex(byte
>> 4, alphabase
));
46 out
.putch(tohex(byte
& 15, alphabase
));
52 /***** WvHexDecoder *****/
54 WvHexDecoder::WvHexDecoder()
60 bool WvHexDecoder::_reset()
68 bool WvHexDecoder::_encode(WvBuf
&in
, WvBuf
&out
, bool flush
)
70 while (in
.used() != 0)
72 char ch
= (char) in
.getch();
75 int digit
= fromhex(ch
);
76 if ( (issecond
= ! issecond
) )
79 out
.putch(first
<< 4 | digit
);
84 seterror("invalid character '%s' in hex input", ch
);
87 if (flush
&& issecond
)
88 return false; // not enough hex digits supplied
93 /*** Compatibility ***/
95 void hexify(char *obuf
, const void *ibuf
, size_t len
)
97 size_t outlen
= len
* 2 + 1;
98 WvHexEncoder(false /*use_uppercase*/).
99 flushmemmem(ibuf
, len
, obuf
, & outlen
);
104 void unhexify(void *obuf
, const char *ibuf
)
106 size_t inlen
= strlen(ibuf
);
107 size_t outlen
= inlen
/ 2;
108 WvHexDecoder().flushmemmem(ibuf
, inlen
, obuf
, & outlen
);