Last active
November 15, 2021 19:16
-
-
Save Miliox/f342ceeb5548e0628715af7c84c71cb3 to your computer and use it in GitHub Desktop.
Plain Base64
This file contains 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> | |
const char kBase64Alphabet[64] = { | |
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', | |
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', | |
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-' | |
}; | |
const char kBase64Padding = '='; | |
int main(int argc, char** argv) | |
{ | |
for (int i = 1; i < argc; i++) | |
{ | |
char buffer = 0; | |
int j = 0; | |
for (int j = 0; ; ++j) | |
{ | |
char ch = argv[i][j]; | |
int rem = j % 3; | |
// 8 - 6; => 2 | |
// 10 - 6; => 4 | |
// 12 - 6; => 6 | |
// 6 - 6; => 0 | |
switch (rem) | |
{ | |
case 0: | |
{ | |
if (ch == 0) | |
{ | |
break; | |
} | |
char sx = ch >> 2; | |
putchar(kBase64Alphabet[sx]); | |
buffer = ch & 0x3; | |
} | |
break; | |
case 1: | |
{ | |
char sx = ((buffer << 4) & 0x30) | (ch >> 4); | |
putchar(kBase64Alphabet[sx]); | |
buffer = ch & 0xf; | |
if (ch == 0) | |
{ | |
putchar(kBase64Padding); | |
putchar(kBase64Padding); | |
break; | |
} | |
} | |
break; | |
case 2: | |
{ | |
char sx = (buffer << 2) | (ch >> 6); | |
putchar(kBase64Alphabet[sx]); | |
if (ch == 0) | |
{ | |
putchar(kBase64Padding); | |
break; | |
} | |
putchar(kBase64Alphabet[ch & 0x3f]); | |
} | |
break; | |
} | |
} | |
putchar('\n'); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment