[轉載] c++中UTF-8到ANSI的轉換

目 前 許 多 數 據 庫 中 數 據 的 存 儲 編 碼 是 Utf-8 格 式 的 , 而 我 們 在 編 程 時 默 認 使 用 的 是 ANSI 編 碼 , 從 數 據 庫 裏 提 取 數 據 時 經 常 會 遇 到 亂 碼 的 情 形 , 如 題 , 提 供 一 個 格 式 轉 換 函 數 , 自 己 寫 的 , 敬 請 各 位 達 人 批 評 指 正 。
//實現編碼由utf-8到ANSI的轉換
char*Utf2ANSI(char*srcCode)
{
    int srcCodeLen=0 ;
    srcCodeLen=MultiByteToWideChar(CP_UTF8,NULL,srcCode,strlen(srcCode),NULL,0);
    wchar_t*result_t=new wchar_t[srcCodeLen+1];
    MultiByteToWideChar(CP_UTF8,NULL,srcCode,strlen(srcCode),result_t,srcCodeLen);
    //utf-8轉換爲Unicode
    result_t[srcCodeLen]='\0' ;
    srcCodeLen=WideCharToMultiByte(CP_ACP,NULL,result_t,wcslen(result_t),NULL,0,NULL,NULL);
    char*result=new char[srcCodeLen+1];
    WideCharToMultiByte(CP_ACP,NULL,result_t,wcslen(result_t),result,srcCodeLen,NULL,NULL);
    //Unicode轉換爲ANSI
    result[srcCodeLen]='\0' ;
    delete result_t ;
    return result ;
}

原文地址:http://bbs.sciencenet.cn/thread-107913-1-1.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章