■ Base64デコード(平成16年午後1問5)
#include <stdio.h>
/* 平成16年午後1問5 */
/* Base64 デコード */
const char base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *_strchr(const char *s, char c)
{
while (*s != '\0') {
if (*s == c) return (char *)s;
s++;
}
return NULL;
}
char _decode(char c1, char c2, int no)
{
char b1, b2, r;
b1 = _strchr(base64, c1) - base64;
b2 = _strchr(base64, c2) - base64;
switch (no) {
case 0:
r = (b1 << 2) | (b2 >> 4);
break;
case 1:
r = (b1 << 4) | (b2 >> 2);
break;
case 2:
r = (b1 << 6) | b2;
break;
}
return r;
}
int main(int argc, char *argv[])
{
int ch, i, n;
char b[3], c[4];
FILE *fi = NULL, *fo = NULL;
if (argc < 3) return -1;
fi = fopen(argv[1], "rt");
fo = fopen(argv[2], "wb");
i = 0;
while (feof(fi) == 0) {
ch = fgetc(fi);
if (ch != '\n') {
c[i] = ch;
i++;
if (i == 4) {
b[0] = _decode(c[0], c[1], 0);
b[1] = _decode(c[1], c[2], 1);
b[2] = _decode(c[2], c[3], 2);
n = 3;
if (c[3] == '=') n = 2;
if (c[2] == '=') n = 1;
fwrite(b, 1, n, fo);
i = 0;
}
}
}
if (i > 0)
printf("入力データの形式が正しくない");
fclose(fi);
fclose(fo);
return 0;
}