Windows下 GBK與UTF8之間的互相轉換(C++)

1.GBK轉UTF8

std::string GBKToUTF8(const char* str_GBK)
{
	int len = MultiByteToWideChar(CP_ACP, 0, str_GBK, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_ACP, 0, str_GBK, -1, wstr, len);
	len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
	std::string strTemp = str;
	if (wstr) delete[] wstr;
	if (str) delete[] str;
	return strTemp;
}

2.UTF8轉GBK

std::string UTF8ToGBK(const char* str_UTF8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, str_UTF8, -1, NULL, 0);
	wchar_t* wsz_GBK = new wchar_t[len + 1];
	memset(wsz_GBK, 0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, str_UTF8, -1, wsz_GBK, len);
	len = WideCharToMultiByte(CP_ACP, 0, wsz_GBK, -1, NULL, 0, NULL, NULL);
	char* sz_GBK = new char[len + 1];
	memset(sz_GBK, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wsz_GBK, -1, sz_GBK, len, NULL, NULL);
	std::string str_temp(sz_GBK);
	if (wsz_GBK) delete[] wsz_GBK;
	if (sz_GBK) delete[] sz_GBK;
	return str_temp;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章