c++ 轉換unicode字符串為js \u格式


唯一注意的就是 大小端問題, PC基本是 LE 

typedef union _uacode
{
    struct {
        BYTE LowByte;
        BYTE HighByte;
    }DUMMYSTRUCTNAME;
    struct {
        BYTE LowByte;
        BYTE HighByte;
    } u;
    wchar_t ch;
}UACODE;
string Unicode2AnsiCode(wstring str)
{
    const wchar_t *p = str.c_str();
    UACODE ua;
    string sResult(str.length()*6+1,'\0');
    char*  pa = &sResult[0];
    for(wstring::const_iterator it = str.begin();it!=str.end();it++)
    {
        ua.ch = *it;
        if(ua.HighByte)
        {
            sprintf_s(pa,7,"\\u%02x%02x",ua.HighByte,ua.LowByte);
            pa+=6;
        }else{
            *pa = ua.LowByte;
            pa++;
        }
        
    }
    return sResult.c_str();
}

 轉換 "經常a中b"

string s = Unicode2AnsiCode(L"經常a中b");
    printf("%s\n",s.c_str());
輸出:  \u7ecf\u5e38a\u4e2db

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM