//首先从UTF8转到UNCODE
//再从UNCODE转到ANSI

int ConvUtf8ToAnsi(CString& strSource, CString& strChAnsi)
{  
    if (strSource.GetLength() <= 0)
        return 0;
   
    CString strWChUnicode;

    strSource.TrimLeft();
    strSource.TrimRight();   
    strChAnsi.Empty();

    int iLenByWChNeed = MultiByteToWideChar(CP_UTF8, 0,
                                            strSource.GetBuffer(0),
                                            strSource.GetLength(), //MultiByteToWideChar
                                            NULL, 0);

    int iLenByWchDone = MultiByteToWideChar(CP_UTF8, 0,
                                            strSource.GetBuffer(0),
                                            strSource.GetLength(),
                                            (LPWSTR)strWChUnicode.GetBuffer(iLenByWChNeed * 2),
                                            iLenByWChNeed); //MultiByteToWideChar
   
    strWChUnicode.ReleaseBuffer(iLenByWchDone * 2);

    int iLenByChNeed  = WideCharToMultiByte(CP_ACP, 0,
                                            (LPCWSTR)strWChUnicode.GetBuffer(0),
                                            iLenByWchDone,
                                            NULL, 0,
                                            NULL, NULL); 
   
    int iLenByChDone  = WideCharToMultiByte(CP_ACP, 0,
                                            (LPCWSTR)strWChUnicode.GetBuffer(0),
                                            iLenByWchDone,
                                            strChAnsi.GetBuffer(iLenByChNeed),
                                            iLenByChNeed,
                                            NULL, NULL);

    strChAnsi.ReleaseBuffer(iLenByChDone);
   
    if (iLenByWChNeed != iLenByWchDone || iLenByChNeed != iLenByChDone)
        return 1;

    return 0;   
}
posted on 2011-05-24 19:46  °ι 、曲 终  阅读(2610)  评论(0编辑  收藏  举报