如何将一串字符在Unicode和UTF8之间互相转换?最好有源码,能讲解原理也行。

解决方案 »

  1.   

    LdapUnicodeToUTF8
    LdapUTF8ToUnicodeHeader: Declared in Winldap.h.
    Library: Use Wldap32.lib.
      

  2.   

    Knowledge Base article Q175392 "INFO: UTF8 Support" says:"Windows NT4.0 supports Unicode<->UTF8 translation via
    MultiByteToWideChar()/WideCharToMultiByte(), using CP_UTF8 for the
    CodePage parameter,
    utf8ToUnicode() is a function that converts a utf8 string (char
    array)
       to a UNICODE string (wchar_t array) based on the utf8 specification
      

  3.   

    Knowledge Base article Q175392 "INFO: UTF8 Support" says:"Windows NT4.0 supports Unicode<->UTF8 translation via
    MultiByteToWideChar()/WideCharToMultiByte(), using CP_UTF8 for the
    CodePage parameter,
    utf8ToUnicode() is a function that converts a utf8 string (char
    array)
       to a UNICODE string (wchar_t array) based on the utf8 specification
      

  4.   

    MultiByteToWideChar不管用,不知道是不是我用错了。
    CString szText = "中华人民共和国";int nLen = MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, (LPCTSTR)szText, szText.GetLength(), NULL, 0);
    //此处获得的nLen为什么老是等于0 ??
    if(nLen > 0){
    LPWSTR m_pUTF8 = new WCHAR[nLen]; // 分配内存
    MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, (LPCTSTR)m_strListing, m_strListing.GetLength(), m_pUTF8, nLen); 
    }
      

  5.   

    OK我弄明白了Translate using UTF-8. When this is set, dwFlags must be zero.
      

  6.   

    WideCharToMultiByte和WideCharToMultiByte不能处理中文字符吗? char *pszText=new char[128];
    memset(pszText, 0, 128);
    strcpy(pszText, "中华人民共和国");
    //此名如果strcpy(pszText, "abcdefg");则可以还原
    int nUnicodeLen = MultiByteToWideChar(CP_UTF8, 0, pszText, -1, NULL, 0);
    wchar_t *pUTF8=NULL; if(nUnicodeLen > 0){
    pUTF8 = (wchar_t*)malloc(sizeof(wchar_t)*(nUnicodeLen+1)); MultiByteToWideChar(CP_UTF8, 0, pszText, strlen(pszText), pUTF8, nUnicodeLen); 
    } char *pszEncode=new char[128];
    memset(pszEncode, 0, 128);
    WideCharToMultiByte(CP_UTF8, 0, pUTF8, nUnicodeLen, pszEncode, 128, NULL, NULL);
    //如果最上面的pszText中是中文字符的话,pszEncode中解出来的是乱七八糟的东西,如果是英文数字则没有问题。 delete []pszText;pszText=NULL;
    delete []pszEncode;pszEncode=NULL;