Skip to content

Instantly share code, notes, and snippets.

@JaHIY
Last active September 11, 2015 04:41
Show Gist options
  • Save JaHIY/0783a9fdf0a49e673f1a to your computer and use it in GitHub Desktop.
Save JaHIY/0783a9fdf0a49e673f1a to your computer and use it in GitHub Desktop.
base64 in C language
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
int main(void) {
const uint8_t base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint32_t buf = 0;
int8_t iter = 0;
bool enter_loop = true;
while (enter_loop) {
int16_t input = getchar();
uint8_t *p = NULL;
switch(input) {
case EOF:
case '=':
enter_loop = false;
continue;
default:
p = (uint8_t *)strchr((const char *)base64chars, input);
if (p == NULL) { continue; }
uint8_t c = p - base64chars;
buf = (buf << 6) | c;
iter += 1;
if (iter == 4) {
for (int_fast8_t i=16; i>=0; i-=8) {
putchar((buf >> i) & 255);
}
iter = buf = 0;
}
break;
}
}
switch (iter) {
case 2:
putchar((buf >> 4) & 255);
break;
case 3:
for (int_fast8_t i=10; i>=0; i-=8) {
putchar((buf >> i) & 255);
}
break;
}
return 0;
}
#include <stdio.h>
#include <stdint.h>
int main(void) {
const uint8_t base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint32_t buf = 0;
int_fast8_t iter = 0;
uint_fast8_t len = 0;
while (1) {
int16_t input = getchar();
if (input == EOF) { break; }
buf = (buf << 8) | ((uint8_t)input & 255);
iter += 1;
if (len == 76) {
printf("%s", "\r\n");
len = 0;
}
if (iter == 3) {
for (int_fast8_t i=18; i>=0; i-=6) {
putchar(base64chars[(uint8_t)(buf >> i) & 63]);
}
iter = buf = 0;
len += 4;
}
}
if (iter > 0) {
uint_fast8_t p = 3 - iter;
switch (iter) {
case 1:
buf <<= 4;
break;
case 2:
buf <<= 2;
break;
}
while (1) {
putchar(base64chars[(uint8_t)(buf >> (iter*6)) & 63]);
iter -= 1;
if (iter < 0) { break; }
}
while (1) {
putchar('=');
p -= 1;
if (p == 0) { break; }
}
}
printf("%s", "\r\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment