Last active
September 11, 2015 04:41
-
-
Save JaHIY/0783a9fdf0a49e673f1a to your computer and use it in GitHub Desktop.
base64 in C language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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