トップ 履歴 一覧 カテゴリ ソース 検索 ヘルプ RSS ログイン

ScrapCode/C/BASE64

INDEX

BASE64 エンコード・デコード

覚書・未検証です。

 概要

BASE64は、バイナリデータなどを7ビットASCIIだけの文字列に変換する。電子メールの添付など各種のインターネットで使用されています。

変換方法は、3バイト(24ビット)ごとにデータを、6ビットごと分割してASCIIだけの4文字に置き換えます。

 ソース

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
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
52
53
54
55
56
57
58
59
60
61
/* BASE64変換テーブル */
const static char BASE64[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/=";

/* デコード */
unsigned char* base64Encode(unsigned char *source, int size){
    unsigned char* result = NULL;
    unsigned char ind1,ind2,ind3,ind4;
    int i,j;

    /* 結果領域 */
    result = calloc(sizeof(char), size + 3);

    for( i = 0, j = 0 ; i < size ; i += 4 ){
        /* 文字コード値取得 */
        ind1 = *(source + i + 0) == '=' ? 0 : strchr(BASE64, *(source + i + 0)) - BASE64;
        ind2 = *(source + i + 1) == '=' ? 0 : strchr(BASE64, *(source + i + 1)) - BASE64;
        ind3 = *(source + i + 2) == '=' ? 0 : strchr(BASE64, *(source + i + 2)) - BASE64;
        ind4 = *(source + i + 3) == '=' ? 0 : strchr(BASE64, *(source + i + 3)) - BASE64;
        /* デコード */
        *(result + j + 0) = (unsigned char)( (ind1 & 0x3f) << 2 | (ind2 & 0x30) >> 4 );
        *(result + j + 1) = (unsigned char)( (ind2 & 0x0f) << 4 | (ind3 & 0x3c) >> 2 );
        *(result + j + 2) = (unsigned char)( (ind3 & 0x03) << 6 | (ind4 & 0x3f) >> 0 );
        j += 3;
    }

    return(result);
}

/* エンコード */
unsigned char* base64Encode(unsigned char *source, int size){
    unsigned char* result = NULL;
    unsigned char buf1,buf2,buf3;
    unsigned char ind1,ind2,ind3,ind4;
    int i,j;

    /* 結果領域 */
    result = calloc(sizeof(char), size * 2);

    for( i = 0, j = 0 ; i < size ; i += 3 ){
        /* 文字コード値取得 */
        buf1 = (i < size - 0) ? *(source + i + 0) : '\0';
        buf2 = (i < size - 1) ? *(source + i + 1) : '\0';
        buf3 = (i < size - 2) ? *(source + i + 2) : '\0';
        /* 3文字=>4文字へ分解 */
        ind1 =                      (buf1 >> 2);
        ind2 = (buf1 & 0x03) << 4 | (buf2 >> 4);
        ind3 = (buf2 & 0x0f) << 2 | (buf3 >> 6);
        ind4 = (buf3 & 0x3f);
        /* エンコード */
        *(result + j + 0) = BASE64[ind1];
        *(result + j + 1) = BASE64[ind2];
        *(result + j + 2) = ( i < size - 1 ) ? BASE64[ind3] : '=';
        *(result + j + 3) = ( i < size - 2 ) ? BASE64[ind4] : '=';
        j += 4;
    }

    return(result);
}

最終更新時間:2008年11月17日 20時18分00秒 指摘や意見などあればSandBoxのBBSへ。