Created
August 24, 2014 19:05
-
-
Save Koasing/b2eb9a07a41263038bc9 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
static const char *BASE64STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |
int getBase64Length(int len) | |
{ | |
return (len+2)/3*4; | |
} | |
static void b64(char in1, char in2, char in3, char *out) | |
{ | |
/* | |
bytes 012345 67 0123 4567 01 234567 | |
base64 234567 23 4567 2345 67 234567 | |
*/ | |
char base64[4] = {0,}; | |
base64[0] = ( in1 >> 2 ) & 0x3F; | |
base64[1] = ( ( in1 << 4 ) & 0x30 ) | ( ( in2 >> 4 ) & 0x0F ); | |
base64[2] = ( ( in2 << 2 ) & 0x3C ) | ( ( in3 >> 6 ) & 0x03 ); | |
base64[3] = ( in3 ) & 0x3F; | |
out[0] = BASE64STR[base64[0]]; | |
out[1] = BASE64STR[base64[1]]; | |
out[2] = BASE64STR[base64[2]]; | |
out[3] = BASE64STR[base64[3]]; | |
} | |
int getBase64(const char *in, int in_len, char *out, int out_len, char padding) | |
{ | |
int cursor = 0; | |
if( in_len < 0) return 0; | |
if(out_len < getBase64Length(in_len)) return -1; | |
// three bytes bundle | |
for(cursor = 2; cursor < in_len; cursor += 3) { | |
b64(in[cursor-2], in[cursor-1], in[cursor], out); | |
out += 4; | |
} | |
// tail bytes | |
if(cursor == in_len ) { b64(in[cursor-2], in[cursor-1], 0, out); out[3] = padding; } | |
if(cursor == in_len +1) { b64(in[cursor-2], 0, 0, out); out[2] = out[3] = padding; } | |
if(cursor == in_len +2) { /* do nothing */ } | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment