00001
00002
00003
00004
00005
00006
00007
#include "wvhex.h"
00008
#include <ctype.h>
00009
00010 static inline char tohex(
int digit,
char alphabase)
00011 {
00012
return (digit < 10 ?
'0' : alphabase) + digit;
00013 }
00014
00015 static inline int fromhex(
char digit)
00016 {
00017
if (isdigit(digit))
00018
return digit -
'0';
00019
if (isupper(digit))
00020
return digit -
'A' + 10;
00021
return digit -
'a' + 10;
00022 }
00023
00024
00025
00026 WvHexEncoder::WvHexEncoder(
bool use_uppercase)
00027 {
00028 alphabase = (use_uppercase ?
'A' :
'a') - 10;
00029
_reset();
00030 }
00031
00032
00033 bool WvHexEncoder::_reset()
00034 {
00035
return true;
00036 }
00037
00038
00039 bool WvHexEncoder::_encode(
WvBuf &in,
WvBuf &out,
bool flush)
00040 {
00041
while (in.
used() != 0)
00042 {
00043
unsigned char byte = in.
getch();
00044 out.
putch(
tohex(byte >> 4, alphabase));
00045 out.
putch(
tohex(byte & 15, alphabase));
00046 }
00047
return true;
00048 }
00049
00050
00051
00052
00053 WvHexDecoder::WvHexDecoder()
00054 {
00055
_reset();
00056 }
00057
00058
00059 bool WvHexDecoder::_reset()
00060 {
00061 issecond =
false;
00062 first = 0;
00063
return true;
00064 }
00065
00066
00067 bool WvHexDecoder::_encode(
WvBuf &in,
WvBuf &out,
bool flush)
00068 {
00069
while (in.
used() != 0)
00070 {
00071
char ch = (
char) in.
getch();
00072
if (isxdigit(ch))
00073 {
00074
int digit =
fromhex(ch);
00075
if ( (issecond = ! issecond) )
00076 first = digit;
00077
else
00078 out.
putch(first << 4 | digit);
00079
continue;
00080 }
00081
if (isspace(ch))
00082
continue;
00083 seterror(
"invalid character '%s' in hex input", ch);
00084
return false;
00085 }
00086
if (flush && issecond)
00087
return false;
00088
return true;
00089 }
00090
00091
00092
00093
00094 void hexify(
char *obuf,
const void *ibuf, size_t len)
00095 {
00096 size_t outlen = len * 2 + 1;
00097
WvHexEncoder(
false ).
00098 flushmemmem(ibuf, len, obuf, & outlen);
00099 obuf[outlen] =
'\0';
00100 }
00101
00102
00103 void unhexify(
void *obuf,
const char *ibuf)
00104 {
00105 size_t inlen = strlen(ibuf);
00106 size_t outlen = inlen / 2;
00107
WvHexDecoder().flushmemmem(ibuf, inlen, obuf, & outlen);
00108 }