Created
July 23, 2013 17:47
-
-
Save AdamBrouwersHarries/6064490 to your computer and use it in GitHub Desktop.
encodes a string from ascii to base64
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
b64_char conv_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\\="; | |
//returns a base 64 string (malloc allocated) | |
b64_string ascii_to_base_64(ascii_string as, int ascii_char_count) | |
{ | |
//find how many ascii blocks of 3 we have (rounded up) | |
int three_blocks_in = (ascii_char_count/3)+(ascii_char_count%3?1:0); | |
//from that, how many base 64 blocks? | |
int characters_out = three_blocks_in*4; | |
//allocate b64 space | |
b64_string out_string = malloc(sizeof(b64_char)*(characters_out+1)); | |
for(int i = 0;i<three_blocks_in;i++) | |
{ | |
b64_char b64A, b64B, b64C, b64D; | |
b64A = b64B = b64C = b64D = 0; | |
//get first b64 character | |
b64A |= ((as[i*3])&0b11111100)>>2; | |
b64B |= ((as[i*3])&0b00000011)<<4; | |
//if last trio only has first ascii character | |
if((i*3)+1 < ascii_char_count) | |
{ | |
b64B |= (as[(i*3)+1]&0b11110000)>>4; | |
b64C |= (as[(i*3)+1]&0b00001111)<<2; | |
}else{ | |
//set it equal to 64 - padding | |
b64C = b64D = 0b01000000; | |
} | |
//if last trio only has first two ascii chars | |
if((i*3)+2 < ascii_char_count) | |
{ | |
b64C |= (as[(i*3)+2]&0b11000000)>>6; | |
b64D |= as[(i*3)+2]&0b00111111; | |
}else{ | |
b64D = 0b01000000; | |
} | |
out_string[(i*4)] = b64A; | |
out_string[(i*4)+1] = b64B; | |
out_string[(i*4)+2] = b64C; | |
out_string[(i*4)+3] = b64D; | |
} | |
out_string[characters_out]='\0'; | |
return out_string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment