【vs2010-MFC】ANSI本地编码和utf16的16进制内码相互转换

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;
}

 

字符编码:https://www.cnblogs.com/notbecoder/p/4840783.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值