aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authortomsmeding <tom.smeding@gmail.com>2016-10-12 22:42:25 +0200
committertomsmeding <tom.smeding@gmail.com>2016-10-12 22:57:43 +0200
commitb9fd7bda32613c44bbf11d9c019d0c28e70c4064 (patch)
tree6d5f43883c1b91ef57d458f898abb5e58a5468e1
parentfa5696d2a1ec781bc3f7ff197ebf0c0019bb56c4 (diff)
Comment base64
-rw-r--r--base64.cpp11
1 files changed, 7 insertions, 4 deletions
diff --git a/base64.cpp b/base64.cpp
index 7e0524a..a6a85e9 100644
--- a/base64.cpp
+++ b/base64.cpp
@@ -6,7 +6,7 @@ using namespace std;
namespace Base64{
char alphabet[65]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- uint8_t revbet[128]={
+ uint8_t revbet[128]={ //reverse look-up table of `alphabet` (for decoding)
#define XX (127)
XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX, //0-15
XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX,XX, //16-31
@@ -19,6 +19,8 @@ namespace Base64{
#undef XX
};
+ //This is the standard base64 algorithm; most of the code deals with correct padding, actually.
+ //There are a lot of magic numbers here, but they should be obvious regarding the algorithm.
string encode(const string &data){
int sz=data.size();
if(sz==0)return {};
@@ -50,24 +52,25 @@ namespace Base64{
return res;
}
+ //The inverse of `encode`.
string decode(const string &dataS){
int szS=dataS.size();
if(szS==0)return {};
uint8_t data[szS];
int sz=0;
- for(char c : dataS){
+ for(char c : dataS){ //First filter away all non-base64 characters (probably mostly newlines, if any)
if(revbet[c&0x7f]!=127)data[sz++]=revbet[c&0x7f];
}
int blocks=sz/4;
int endlen;
- if(sz%4==0){
+ if(sz%4==0){ //Detect padding; tries to be nice and forgive bad padding
if(data[sz-1]=='='){
blocks--;
if(data[sz-2]=='=')endlen=1;
else endlen=2;
} else endlen=0;
- } else endlen=sz%4-1;
+ } else endlen=sz%4-1; //padding not present... assume the data is OK sort-of?
string res(3*blocks+endlen,'\0');
int x;
for(int i=0;i<blocks;i++){