c++ 转换unicode字符串为js \u格式

时间:2021-10-31 20:19:35

唯一注意的就是 大小端问题, 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