ArchBlackmann irc bot - works in ReactOS - happy hacking
[reactos.git] / rosapps / games / ArchBlackmann / base64.cpp
1 // base64.cpp
2
3 #include "base64.h"
4
5 using std::string;
6
7 static const char* alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
8
9 string base64_encode ( const string& sInput )
10 {
11 unsigned char x=0, topbit=0;
12 int v=0;
13 string sOutput;
14 do
15 {
16 if ( topbit < 6 )
17 {
18 x++;
19 v <<= 8;
20 if ( x <= sInput.length() ) v += sInput[x-1];
21 topbit += 8;
22 }
23 topbit -= 6;
24 if ( x > sInput.length() && !v )
25 break;
26 sOutput += alfabet[(v >> topbit) & 63];
27 v &= (1 << topbit) - 1;
28 } while ( x < sInput.length() || v );
29 int eq = (8 - (sOutput.length() % 4)) % 4;
30 while ( eq-- )
31 sOutput += '=';
32 return sOutput;
33 }
34
35 string base64_decode ( const string& sInput )
36 {
37 unsigned char x=0, topbit=0;
38 int v=0, inlen = sInput.length();
39 string sOutput;
40 while ( inlen && sInput[inlen-1] == '=' )
41 inlen--;
42 do
43 {
44 while ( topbit < 8 )
45 {
46 x++;
47 v <<= 6;
48 if ( x <= inlen ) v += (strchr(alfabet, sInput[x-1]) - alfabet);
49 topbit += 6;
50 }
51 topbit -= 8;
52 if ( x > inlen && !v )
53 break;
54 sOutput += (char)((v >> topbit) & 255);
55 v &= ((1 << topbit) - 1);
56 } while ( x <= inlen || v );
57 return sOutput;
58 }