#include char cb64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /* lookup table */ unsigned char encoding_string[] = "Das ist ein Test!?!"; /* what do you want to encode today?*/ int length = 19; /* number of characters entered above*/ unsigned char encode_first_output(unsigned char first){ return first >> 2; } unsigned char encode_second_output(unsigned char first, unsigned char second) { return ((first & 0x03) << 4) | ((second)>> 4); } unsigned char encode_third_output(unsigned char second, unsigned char third) { return ((second & 0x0f) << 2) | ((third) >> 6); } unsigned char encode_fourth_output(unsigned char third) { return (third & 0x3f); } int main(void) { int walker = 0; int no_padding_length = (length / 3) * 3; /* the biggest by 3 dividable integer smaller than length*/ int num_padding = length % 3; int output_length = ((((no_padding_length)/3 )*4) +1); /* 3 bytes input will become 4 bytes output, 1 char as string terminator*/ char last_char, penultimate_char; if (num_padding) /* our output will be 4 bytes larger, if there was a remainder in num_padding */ { output_length += 4; } char base64string[output_length]; /* the output will be stored here*/ base64string[output_length-1] = '\0'; /* to be able to use printf we need a \0 at the end of our output*/ for(walker = 0; walker < no_padding_length / 3; walker = walker+1 ) { unsigned char first_input = encoding_string[walker*3]; unsigned char second_input = encoding_string[walker*3 + 1]; unsigned char third_input = encoding_string[walker*3 + 2]; /* calculate 4 bytes of output and lookup char */ base64string[walker*4] = cb64[encode_first_output(first_input)]; base64string[(walker*4) + 1] = cb64[encode_second_output(first_input, second_input)]; base64string[(walker*4) + 2] = cb64[encode_third_output(second_input, third_input)]; base64string[(walker*4) + 3] = cb64[encode_fourth_output(third_input)]; } switch(num_padding){ /* in case the string was not divideable by 3, we need to do padding */ case 0: break; case 1: last_char = encoding_string[length-1]; base64string[output_length-5] = cb64[encode_first_output(last_char)]; base64string[output_length-4] = cb64[encode_second_output(last_char, 0)]; base64string[output_length-3] = '='; base64string[output_length-2] = '='; break; case 2: penultimate_char = encoding_string[length-2]; last_char = encoding_string[length-1]; base64string[output_length-5] = cb64[encode_first_output(penultimate_char)]; base64string[output_length-4] = cb64[encode_second_output(penultimate_char, last_char)]; base64string[output_length-3] = cb64[encode_third_output(last_char, 0)]; base64string[output_length-2] = '='; break; } printf(base64string); /* print the result*/ printf("\n"); /* a new line makes the output nicer*/ }