version 0.0.1
[fms.git] / src / hex.cpp
1 #include "../include/hex.h"\r
2 \r
3 #ifdef XMEM\r
4         #include <xmem.h>\r
5 #endif\r
6 \r
7 namespace Hex\r
8 {\r
9         \r
10 static const std::string hexchars="0123456789ABCDEF";\r
11 \r
12 const bool Encode(const std::vector<unsigned char> &data, std::string &encoded)\r
13 {\r
14         for(std::vector<unsigned char>::const_iterator i=data.begin(); i!=data.end(); i++)\r
15         {\r
16                 encoded.push_back(hexchars[(((*i)>>4) & 0x0F)]);\r
17                 encoded.push_back(hexchars[((*i) & 0x0F)]);\r
18         }\r
19         return true;\r
20 }\r
21 \r
22 const bool Decode(const std::string &encoded, std::vector<unsigned char> &data)\r
23 {\r
24 \r
25         std::string::size_type pos=0;\r
26         unsigned char byte;\r
27         int bytepart=0;\r
28         \r
29         pos=encoded.find_first_of(hexchars);\r
30         \r
31         while(pos!=std::string::npos)\r
32         {\r
33                 if(bytepart==0)\r
34                 {\r
35                         byte=(hexchars.find(encoded[pos]) << 4) & 0xF0;\r
36                         bytepart=1;\r
37                 }\r
38                 else\r
39                 {\r
40                         byte|=hexchars.find(encoded[pos]) & 0x0F;\r
41                         data.push_back(byte);\r
42                         bytepart=0;\r
43                 }\r
44                 pos=encoded.find_first_of(hexchars,pos+1);\r
45         }\r
46         return true;\r
47 }\r
48 \r
49 }       // namespace\r