Last active
December 19, 2015 22:39
-
-
Save cmouse/6029348 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int base64num(int ch) { | |
if (ch == '=') return 0; | |
if (ch == '/') return 63; // bug was these | |
if (ch == '+') return 62; // two lines | |
if (ch >= 'a') return ch-'a'+26; | |
if (ch >= 'A') return ch-'A'; | |
if (ch >= '0') return ch-'0'+52; | |
return 0; | |
} | |
size_t base642raw(const char *input, size_t ilen, unsigned char *output, size_t olen) | |
{ | |
if (!ilen||ilen%4) return 0; // bad input | |
size_t i,o,k; | |
uint32_t n=0; | |
int rem = 0; | |
for(i=0,o=0;i<ilen && o+3<olen;i+=4) { | |
n=(base64num(input[i])<<18)+(base64num(input[i+1])<<12)+(base64num(input[i+2])<<6)+base64num(input[i+3]); | |
// decode 3 chars | |
output[o]=(n>>16)&0xff; o++; | |
output[o]=(n>>8)&0xff; o++; | |
output[o]=n&0xff; o++; | |
} | |
// handle remainder | |
for(k=ilen-4;k<ilen;k++) rem += (input[k]=='='); | |
return o-rem; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment