Skip to content

Instantly share code, notes, and snippets.

@musou1500
Created March 10, 2022 17:49
Show Gist options
  • Save musou1500/ec00435155566bbc113fdde62b7b7715 to your computer and use it in GitHub Desktop.
Save musou1500/ec00435155566bbc113fdde62b7b7715 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
unsigned char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *b64_encode(unsigned char *s, int len) {
int bit_len = len * 8;
int dest_len = bit_len / 6 + (bit_len % 6 != 0);
int res_len = dest_len + (dest_len % 4 != 0) * (4 - dest_len % 4);
char *res = (char *)malloc(res_len + 1);
res[res_len] = '\0';
for (int i = 0; i < res_len; i++) {
if (i >= dest_len) {
res[i] = '=';
continue;
}
unsigned char mask = (1 << 6) - 1;
int offset = i * 6 % 8;
char table_idx;
if (offset == 0) {
table_idx = s[i * 6 / 8] >> 2 & mask;
} else {
table_idx = s[i * 6 / 8] << offset;
table_idx = table_idx >> 2 & mask;
if (offset > 2) {
int next = i * 6 / 8 + 1;
int next_sz = offset - 2;
if (len > next) {
table_idx |= s[next] >> (10 - offset);
}
}
}
res[i] = base64_table[table_idx];
}
return res;
}
int main(int argc, char *argv[])
{
unsigned char *s = "ABCDEFG";
char *enc = b64_encode(s, strlen(s));
printf("%s\n", enc);
free(enc);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment