BASE64のエンコード/デコードをC言語で書いた。
static const char BASE64_ENC[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char BASE64_DEC[] = {
62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
int encodeBase64(unsigned char* bin_buff, char* asc_buff, int size)
{
int i;
int j = 0;
unsigned short reg = 0;
int len = 0;
short six = 0;
for(i = 0; i < size; i++)
{
reg = (reg << 8) | bin_buff[i];
len += 8;
while(len >= 6)
{
six = (reg >> (len - 6)) & 0x3F;
len -= 6;
asc_buff[j] = BASE64_ENC[six];
j++;
}
}
if(len > 0)
{
six = (reg << (6 - len)) & 0x3F;
asc_buff[j] = BASE64_ENC[six];
j++;
}
while( (j % 4) != 0 )
{
asc_buff[j] = '=';
j++;
}
return j;
}
int decodeBase64(unsigned char* bin_buff, char* asc_buff, int size)
{
int i = 0;
int j = 0;
int m;
char asc;
char reg[4];
while(i < size)
{
for(m = 0; m < 4; m++)
{
asc = asc_buff[i++];
reg[m] = BASE64_DEC[ asc - '+'];
if(reg[m] < 0) return -1;
}
bin_buff[j++] = ((reg[0] & 0x3F) << 2) | ((reg[1] & 0x30) >> 4);
bin_buff[j++] = ((reg[1] & 0x0F) << 4) | ((reg[2] & 0x3C) >> 2);
bin_buff[j++] = ((reg[2] & 0x03) << 6) | ((reg[3] & 0x3F) >> 0);
}
if(asc_buff[i-1] == '=') j--;
if(asc_buff[i-2] == '=') j--;
return j;
}
#if 1
#include<stdio.h>
#define MAX_INPUT_SIZE 15000
#define MAX_OUTPUT_SIZE 20000
int main(void)
{
FILE *infile;
infile = fopen("input.bin", "rb");
if(infile == NULL){
printf("Can not open input file!\n");
return 1;
}
unsigned char inbuff[MAX_INPUT_SIZE];
int inputsize = fread(inbuff, 1, MAX_INPUT_SIZE, infile);
printf("input size = %d bytes\n", inputsize);
fclose(infile);
char outbuff[MAX_OUTPUT_SIZE];
int outputsize = encodeBase64(inbuff, outbuff, inputsize);
printf("output size = %d bytes\n", outputsize);
FILE *outfile;
outfile = fopen("output.txt", "w");
if(outfile == NULL){
printf("Can not open output file!\n");
return 2;
}
int i;
for(i=0;i<outputsize;i++){
fputc(outbuff[i], outfile);
}
fclose(outfile);
return 0;
}
#endif
#if 0
#endif