CString ANSIToUTF16(CString ansiStr){
CString utf16Str;
//前面ascii部分直接使用字符本身
int count = ansiStr.GetLength();
int j;
for (j = 0; j < count; j++)
{
if (ansiStr[j] < 0x80 && ansiStr[j] > 0x0)
{
j++;
}else{
break;
}
}
CString ascllStr = ansiStr.Left(j);
ansiStr = ansiStr.Right(count - j);
//ansi到utf-8
int i= MultiByteToWideChar(CP_ACP, 0, (char*)ansiStr.GetBuffer(0) ,-1 ,NULL,0);
WCHAR* strA = new WCHAR[i];
MultiByteToWideChar(CP_ACP, 0, (char*)ansiStr.GetBuffer(0), -1, strA, i);
i = WideCharToMultiByte(CP_UTF8,0,strA,-1,NULL,0,NULL,NULL);
char *strB = new char[i];
WideCharToMultiByte(CP_UTF8,0,strA,-1,strB,i,NULL,NULL);
//utf-8到utf-16
i = MultiByteToWideChar(CP_UTF8, 0 ,strB ,-1 , NULL, 0);
WCHAR* strC = new WCHAR[i];
MultiByteToWideChar(CP_UTF8, 0, strB, -1, strC, i);
//转为16进制编码
ansiStr = "";
for (int n = 0; n < i - 1; n++)
{
CString tempUtf16;
tempUtf16.Format("\\x%x", strC[n]);
ansiStr.Append(tempUtf16);
}
utf16Str = ascllStr + ansiStr;
delete[] strA;
delete[] strB;
delete[] strC;
return utf16Str;
}
CString UTF16ToANSI(const CString strUtf8){
CString strText(_T(strUtf8));
int pos = strText.Find("\\x");
CString appendStr = "";
if (pos != -1)
{
appendStr = strText.Left(pos);//ascii字符
strText = strText.Right(strText.getLength() - pos);
}
int nCount = strText.Replace(_T("\\x"), _T(" 0x"));
wchar_t* buf = new wchar_t[nCount+1];
memset(buf, 0, sizeof(wchar_t)*(nCount+1));
int nIndex = 0;
TCHAR seps[] = _T(" ");
TCHAR* token = _tcstok(strText.GetBuffer(strText.GetLength()), seps);
while(NULL != token)
{
buf[nIndex++] = _tcstoul(token, NULL, 16);
token = _tcstok(NULL, seps);
}
strText.ReleaseBuffer();
CString ansiStr = appendStr + buf;
delete[] buf;
buf = NULL;
return ansiStr;
}