VC: MBCS字符集转换成UTF-8

// MBCS字符集转换成UTF-8,使用完了之后要释放返回的内存!
char* DataStore::MBCS2Utf8(char* szMBCS, ULONG* _out_length)
{
	if (szMBCS == NULL || _out_length == NULL)
		return NULL;
	// 方法:先转换成CP_ACP再转换成CP_UTF8
	int nLength = MultiByteToWideChar(CP_ACP, 0, szMBCS, -1, NULL, NULL);	// 获取缓冲区长度,再分配内存
	WCHAR *tch = new WCHAR[nLength];
	
	nLength = MultiByteToWideChar(CP_ACP, 0, szMBCS, -1, tch, nLength);		// 将MBCS转换成Unicode

	int nUTF8len = WideCharToMultiByte(CP_UTF8, 0, tch, nLength, 0, 0, 0, 0);	// 获取UTF-8编码长度
	char *utf8_string = new char[nUTF8len];
	WideCharToMultiByte(CP_UTF8, 0, tch, nLength, utf8_string, nUTF8len, 0, 0);	//转换成UTF-8编码
	*_out_length = nUTF8len;

	delete tch;
	return utf8_string;
}

  

posted @ 2012-06-11 10:15  特洛伊人  阅读(1831)  评论(0编辑  收藏  举报