UTF-16 to UTF-8 example2
更新日2007年01月30日

UTF-16 to UTF-8 example2
UTF-16 to UTF-8 example2 への文字コード変換のサンプル実装。(Windows APIを使用しない)
MinGW + gcc 環境において動作確認してあります。

Example Code
以下の例は、Utf16ToUtf8()の実装の例です。 [utf16_to_utf8_2.zip]
/*
 * file:Utf16ToUtf8_2.c
 */
/** @file
 * @brief UTF-16 → UTF-8 への変換実装サンプルプログラム。
 * 
 * UTF-16 → UTF-8 への変換実装サンプルプログラムその1。(Windows APIを使用しない)
 * UTF-16にて用意された"data.txt"ファイルを読み込み、
 * UTF-8へと変換、
 * "out.txt"ファイルへと出力します。
 * 変換後の文字列にBOMが見つかれば、除去します。
 */
/* ビットパターン
 * ┌───────┬───────┬───────────────────────────┬──────────────────┐
 * │フォーマット  │Unicode       │UTF-8ビット列                                         │Unicodeビット列                     │
 * ├───────┼───────┼───────────────────────────┼──────────────────┤
 * │1バイトコード │\u0~\u7f     │0aaabbbb                                              │00000000 0aaabbbb                   │
 * ├───────┼───────┼───────────────────────────┼──────────────────┤
 * │2バイトコード │\u80~\u7ff   │110aaabb 10bbcccc                                     │00000aaa bbbbcccc                   │
 * ├───────┼───────┼───────────────────────────┼──────────────────┤
 * │3バイトコード │\u800~\uffff │1110aaaa 10bbbbcc 10ccdddd                            │aaaabbbb ccccdddd                   │
 * ├───────┼───────┼───────────────────────────┼──────────────────┤
 * │4バイトコード │--------------│11110??? 10?????? 10?????? 10??????                   │未対応                              │
 * ├───────┼───────┼───────────────────────────┼──────────────────┤
 * │5バイトコード │--------------│111110?? 10?????? 10?????? 10?????? 10??????          │未対応                              │
 * ├───────┼───────┼───────────────────────────┼──────────────────┤
 * │6バイトコード │--------------│1111110? 10?????? 10?????? 10?????? 10?????? 10?????? │未対応                              │
 * └───────┴───────┴───────────────────────────┴──────────────────┘
 */
#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef min
#define min(a,b) ((a)<(b)?(a):(b))
#endif
#define DEFAULT_BUFF_LEN 512

int Utf16ToUtf8(char *dest, size_t dest_size, wchar_t *src, size_t src_size);

int main(int argc, char *argv[])
{
    wchar_t     instr[DEFAULT_BUFF_LEN];
    char        outstr[DEFAULT_BUFF_LEN];
    FILE        *pFile;
    long        sizeFile = 0;
    size_t      countRead;
    int         instr_size = 0;
    int         iResult = 0;
    char        *pOutStr = NULL;
    
    /*
     * ファイルより文字列を読み込み
     */
    memset(instr, 0, sizeof(instr));
    pFile = fopen("data.txt", "rb");
    if (pFile == NULL)
    {
        perror("ファイルがひらけません: data.txt");
        return 1;
    }
    fseek(pFile, 0, SEEK_END);
    sizeFile = ftell(pFile);
    fseek(pFile, 0, SEEK_SET);
    countRead = fread(instr, min(sizeFile, DEFAULT_BUFF_LEN), 1, pFile);
    fclose(pFile);
    if (countRead == 0)
    {
        perror("ファイル読み込み失敗: data.txt");
        return 1;
    }
    
    instr_size = min(sizeFile, DEFAULT_BUFF_LEN) * countRead / sizeof(wchar_t);
    
    /*
     * utf16:instr -> utf8:outstr 変換。
     */
    memset(outstr, 0, sizeof(outstr));
    iResult = Utf16ToUtf8(outstr, sizeof(outstr), instr, instr_size);
    if (iResult == FALSE)
    {
        perror("Utf16ToUtf8() Failed.\n");
        return 1;
    }
    printf("%d バイト変換しました。\n", iResult);
    
    pOutStr = outstr;
    /*
     * BOMの除去
     */
    if ((*pOutStr == '\xef') && (*(pOutStr + 1) == '\xbb')
            && (*(pOutStr + 2) == '\xbf'))
    {
        /*
         * UTF-8のBOMはef bb bf
         * LE も BE も存在しないので、BOM付きの場合には除去。
         * BOMが無い場合はそのまま処理。
         */
        /* BOMがある場合にはBOMを無視する */
        pOutStr += 3;
        iResult -= 3;
    }
    
    /*
     * ファイルに文字列を書き込み。
     */
    pFile = fopen("out.txt", "wb");
    if (pFile == NULL)
    {
        perror("ファイルが開けません: out.txt");
        return 1;
    }
    fwrite(pOutStr, iResult, 1, pFile);
    fclose(pFile);
    
    return 0;
}

/**
 * 文字コードをUTF-16よりUTF-8へと変換。
 * 
 * @param[out] dest 出力文字列UTF-8
 * @param[in]  dest_size destのバイト数
 * @param[in]  src 入力文字列UTF-16
 * @param[in]  src_size 入力文字列の文字数
 * 
 * @return 成功時には出力文字列のバイト数を戻します。
 *         dest_size に0を指定し、こちらの関数を呼び出すと、変換された
 *         文字列を格納するのに必要なdestのバイト数を戻します。
 *         関数が失敗した場合には、FALSEを戻します。
 */
int Utf16ToUtf8(char *dest, size_t dest_size, wchar_t *src, size_t src_size)
{
    wchar_t     bom;
    long        countNeedsBytes;
    long        cursor;
    wchar_t     wcWork1;
    long        sizeBytes;
    char       chWork1;
    char       chWork2;
    char       chWork3;
    
    /*
     * 入力パラメータをチェック
     */
    if (dest_size == 0)
    {
        /*
         * dest_size == 0
         */
    }
    else
    {
        /*
         * dest_size != 0
         */
        if (dest == NULL)
        {
            /* Error : dest is NULL. */
            return FALSE;
        }
        if (dest_size < 0)
        {
            /* Error : dest_size < 0. */
            return FALSE;
        }
    }
    if (src == NULL)
    {
        /* Error : src is NULL. */
        return FALSE;
    }
    if (src_size < 0)
    {
        /* Error : src_size < 0. */
        return FALSE;
    }
    
    countNeedsBytes = 0;
    for (cursor = 0; cursor < src_size; cursor++)
    {
        /* srcより1ワードのデータを読み出し */
        wcWork1 = *(src + cursor);
        if (       (wcWork1 <= ((wchar_t)0x007f)))
        {
            /* 0x0000 to 0x007f */
            sizeBytes = 1;
        }
        else if (  (((wchar_t)0x0080) <= wcWork1)
                && (wcWork1 <= ((wchar_t)0x07ff)))
        {
            /* 0x0080 to 0x07ff */
            sizeBytes = 2;
        }
        else if (  (((wchar_t)0x0800) <= wcWork1))
        {
            /* 0x0800 to 0xffff */
            sizeBytes = 3;
        }
        else
        {
            /* Error : unknown code */
            return FALSE;
        }
        
        /*
         * dest_size をチェック
         */
        if (dest_size && (dest_size < (countNeedsBytes + sizeBytes)))
        {
            /* Error : memory is not enough for dest */
            return countNeedsBytes;
        }
        
        /* sizeBytes毎に処理を分岐 */
        if (dest_size) switch (sizeBytes)
        {
        case 1:
            /*
             * ビット列
             * (0aaabbbb)UTF-8 ... (00000000 0aaabbbb)UTF-16
             */
            *dest = (char)wcWork1;              /* 0aaabbbb */
            dest ++;
            break;
        case 2:
            /*
             * ビット列
             * (110aaabb 10bbcccc)UTF-8 ... (00000aaa bbbbcccc)UTF-16
             */
            chWork1 = (char)(wcWork1 >> 6);     /* 000aaabb */
            chWork1 |= (char)0xc0;              /* 110aaabb */
            chWork2 = (char)wcWork1;            /* bbbbcccc */
            chWork2 &= (char)0x3f;              /* 00bbcccc */
            chWork2 |= (char)0x80;              /* 10bbcccc */
            *dest = chWork1;
            dest++;
            *dest = chWork2;
            dest++;
            break;
        case 3:
            /*
             * ビット列
             * (1110aaaa 10bbbbcc 10ccdddd)UTF-8 ... (aaaabbbb ccccdddd)UTF-16
             */
            chWork1 = (char)(wcWork1 >> 12);    /* ????aaaa */
            chWork1 &= (char)0x0f;              /* 0000aaaa */
            chWork1 |= (char)0xe0;              /* 1110aaaa */
            chWork2 = (char)(wcWork1 >> 6);     /* aabbbbcc */
            chWork2 &= (char)0x3f;              /* 00bbbbcc */
            chWork2 |= (char)0x80;              /* 10bbbbcc */
            chWork3 = (char)wcWork1;            /* ccccdddd */
            chWork3 &= (char)0x3f;              /* 00ccdddd */
            chWork3 |= (char)0x80;              /* 10ccdddd */
            *dest = chWork1;
            dest++;
            *dest = chWork2;
            dest++;
            *dest = chWork3;
            dest++;
            break;
        default:
            break;
        }
        countNeedsBytes += sizeBytes;
    }
    
    return countNeedsBytes;
}