C source code for base64 encoding / C source code for base64 decoding
programming/C_C++ 2023. 6. 28. 23:14#include <stdio.h>
#include <stdlib.h>
const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void base64_encode(const char *input, char *output) {
int i, j;
for (i = 0, j = 0; input[i]; i += 3) {
output[j++] = base64_table[input[i] >> 2];
output[j++] = base64_table[((input[i] & 0x03) << 4) | (input[i + 1] >> 4)];
output[j++] = base64_table[((input[i + 1] & 0x0f) << 2) | (input[i + 2] >> 6)];
output[j++] = base64_table[input[i + 2] & 0x3f];
}
output[j] = '\0';
}
int main(void) {
char input[] = "Hello, world!";
char output[1024];
base64_encode(input, output);
printf("Base64 encoded string: %s\n", output);
return 0;
}
==========================
#include <stdio.h>
#include <stdlib.h>
const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void base64_decode(const char *input, char *output) {
int i, j;
for (i = 0, j = 0; input[i]; i += 4) {
output[j++] = (base64_table[input[i]] << 2) | (base64_table[input[i + 1]] >> 4);
if (input[i + 2] != '=') {
output[j++] = ((base64_table[input[i + 1]] & 0x0f) << 4) | (base64_table[input[i + 2]] >> 2);
}
if (input[i + 3] != '=') {
output[j++] = ((base64_table[input[i + 2]] & 0x03) << 6) | base64_table[input[i + 3]];
}
}
output[j] = '\0';
}
int main(void) {
char input[] = "SGVsbG8sIHdvcmxkIQ==";
char output[1024];
base64_decode(input, output);
printf("Base64 decoded string: %s\n", output);
return 0;
}