Skip to content

Instantly share code, notes, and snippets.

@odzhan
Last active November 11, 2023 00:31
Show Gist options
  • Save odzhan/3e2595dc2316645b29b2028fc4ab9401 to your computer and use it in GitHub Desktop.
Save odzhan/3e2595dc2316645b29b2028fc4ab9401 to your computer and use it in GitHub Desktop.
base64
/**
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 2C, 2D, 2E, 2F,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 3A, 3B, 3C, 3D, 3E, 3F,
The two functions just avoid having to use a lookup table for both encoding and decoding.
*/
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
char
base64_encode(int c) {
return (c < 26) ? c + 'A' :
(c < 52) ? (c - 26) + 'a' :
(c < 62) ? (c - 52) + '0' :
(c == 63) ? '/' : '+';
}
char
base64_decode(int c) {
return (c == '+') ? 62 :
(c == '/') ? 63 :
(c <= '9') ? (c - '0') + 52 :
(c <= 'Z') ? (c - 'A') : (c - 'a') + 26;
}
void
base64(size_t outlen, void *inbuf, void *outbuf) {
uint8_t *out = (uint8_t*)outbuf;
uint8_t *in = (uint8_t*)inbuf;
uint32_t x = 0, z = 0;
while (outlen) {
x = (x << 8) | *in++;
z += 8;
while (z >= 6) {
z -= 6;
uint8_t c = (x >> z) & 63;
*out++ = (c < 26) ? c + 'A' : (c < 52) ? (c - 26) + 'a' : (c < 62) ? (c - 52) + '0' : (c == 63) ? '/' : '+';
outlen--;
}
}
}
int
main(void) {
uint8_t data[64]={0}, enc[64]={0}, dec[64]={0};
for (int i=0; i<sizeof(data); i++) {
data[i] = i;
enc[i] = base64_encode(data[i]);
printf("%c", enc[i]);
}
printf("\n");
for (int i=0; i<sizeof(data); i++) {
printf("%02X, ", base64_decode(enc[i]));
if ((i & 15) == 15) putchar('\n');
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment