[转载] 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章