Skip to content

Instantly share code, notes, and snippets.

@reportbase
Created March 22, 2015 20:58
Show Gist options
  • Save reportbase/915f14194e5d72c97832 to your computer and use it in GitHub Desktop.
Save reportbase/915f14194e5d72c97832 to your computer and use it in GitHub Desktop.
Encode binary file base64
inline char* base64_encode(const unsigned char* data, int input_length, int* output_length)
{
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
static int mod_table[] = {0, 2, 1};
*output_length = (size_t)(4.0 * ceil((double) input_length / 3.0));
char* encoded_data = malloc(*output_length);
for(int i = 0, j = 0; i < input_length;)
{
uint32_t octet_a = i < input_length ? data[i++] : 0;
uint32_t octet_b = i < input_length ? data[i++] : 0;
uint32_t octet_c = i < input_length ? data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for(int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[*output_length - 1 - i] = '=';
return encoded_data;
}
inline void echo_base64_encode(const char*, const char* path, void* app_, node<message*>** errors)
{
int size;
unsigned char* buffer = load_binary(path, &size, errors);
if(*errors)
{
push_message(errors, 0, 0, 1, __FILE__, __FUNCTION__, __LINE__, "bad path: %s", path);
return;
}
int len;
char* str = base64_encode(buffer, size, &len);
char ch[LARGE_TEXT_BUFFER];
strncpy(ch, str, len);
ch[len] = '\0';
fprintf(stdout, "imageObj.src = \"data:image/png;base64,%s\"\n", ch);
free(str);
free(buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment