Skip to main content
2 of 4
added 50 characters in body

What do you think of my Base64 encoding implementation?

I am learning C and decided to make an implementation of Base64 encoding according to the info Wikipedia provides about it.

Here are all files, my main question is: should I declare the index_table array inside the get_base64_digit function (static char index_table[] = "blabla") though a general code review would be appreciated.

funcs.c

static char index_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static char get_index_digit(int x) {
    return index_table[x];
}

char get_base64_digit(const unsigned int base64, int digit_number){

    switch (digit_number){
            case 0:
                    return get_index_digit(base64 >> 18);
            case 1:
                    return get_index_digit((base64 >> 12) & 077);
            case 2:
                    return get_index_digit((base64 >> 6) & 077);
            case 3:
                    return get_index_digit(base64 & 077);
    }

    return '\0';
}

funcs.h

#include <stdio.h>
#include <string.h>

char get_base64_digit(unsigned int base64, int digit_number);

main.c

 #include "funcs.h"

int main(int argc, char* argv[]){

    char* text = argc == 2 ? argv[1] : '\0';

    unsigned final, temp;

    int text_len  = strlen(text);
    int remainder = text_len % 3;

    //Iterate over the input string, three characters at a time.
    for (int x = final = temp = 0; x < (remainder == 0 ? text_len : text_len - remainder); x += 3) {

            final = (text[x] << 16) | (text[x+1] << 8) | text[x+2];

            printf("%c%c%c%c",  get_base64_digit(final, 0), get_base64_digit(final, 1), get_base64_digit(final, 2), get_base64_digit(final, 3));

    }

    //Handle the last bytes in case text_len wasn't a multiple of 3
    if (remainder == 1) {
            final = text[text_len-1] << 16; 
            printf("%c%c==\n", get_base64_digit(final, 0), get_base64_digit(final, 1));
    } else if (remainder == 2){ 
            final = (text[text_len-2] << 16) | (text[text_len-1] << 8); 
            printf("%c%c%c=\n",  get_base64_digit(final, 0), get_base64_digit(final, 1), get_base64_digit(final, 2));
    } else
            return 0;


    return 0;

}