1. 程式人生 > >WINDOWS下UTF8/UTF16/ANSI相互轉換

WINDOWS下UTF8/UTF16/ANSI相互轉換

目錄

編碼知識

程式碼演示

/**
* @brief ansi字元轉UTF8字元
* @param pWideBytes 寬字元(utf16編碼)流指標
* @param cchChar 字元數,需要包含終止符數
* @param strResult 轉換結果,儲存utf8位元組流
*/
std::string WideStringToUtf8(const wchar_t* pWideBytes, int cchChar)
{
	//獲取所需緩衝區大小
	int nUtf8Count = WideCharToMultiByte(CP_UTF8, 0, pWideBytes, cchChar, NULL, 0, NULL, NULL);
	if (nUtf8Count == 0)
	{
		return std::string();
	}

	//此處理解:wide char是windows對UTF16的儲存實現,
	//傳遞CP_UTF8是告訴【輸出】的位元組流為UTF8格式,
	//這樣函式內部就知道將UTF16的wide char轉化成什麼格式的位元組流了
	char* pUtf8Buff = new char[nUtf8Count];
	WideCharToMultiByte(CP_UTF8, 0, pWideBytes, cchChar, pUtf8Buff, nUtf8Count, NULL, NULL);
	std::string strResult = pUtf8Buff;
	delete pUtf8Buff;
	return strResult;
}


/**
* @brief utf8字元轉寬字元(utf16編碼)
* @param nBytes 位元組大小,需要包含終止符數
*/
std::wstring Utf8ToWideString(const char* pUtf8Bytes, int nBytes)
{
	//獲取所需緩衝區大小
	int nWideCount = MultiByteToWideChar(CP_UTF8, 0, pUtf8Bytes, nBytes, NULL, 0);
	if (nWideCount == 0)
	{
		return std::wstring();
	}

	//此處理解:wide char是windows對UTF16的儲存實現,
	//傳遞CP_UTF8是告訴【輸入】的位元組流是UTF8格式的,
	//這樣函式內部就知道怎麼將位元組流轉換成utf16的wide char格式了
	wchar_t* pWideBuff = new wchar_t[nWideCount];
	MultiByteToWideChar(CP_UTF8, 0, pUtf8Bytes, nBytes, pWideBuff, nWideCount);
	std::wstring strResult = pWideBuff;
	delete pWideBuff;

	return strResult;
}


/**
* @brief ansi字元轉寬字元(utf16編碼)
* @param nBytes 位元組大小,需要包含終止符數
*/
std::wstring AnsiToWString(const char* pAnsiString, int nBytes)
{
	//獲取所需緩衝區大小
	int nWideCount = MultiByteToWideChar(CP_ACP, 0, pAnsiString, nBytes, NULL, 0);
	if (nWideCount == 0)
	{
		return std::wstring();
	}

	//此處理解:wide char是windows對UTF16的儲存實現,
	//傳遞CP_ACP是告訴【輸入】位元組流是ansi格式的,
	//這樣函式內部就知道怎麼將位元組流轉換成utf16的wide char格式了
	wchar_t* pWideBuff = new wchar_t[nWideCount];
	MultiByteToWideChar(CP_ACP, 0, pAnsiString, nBytes, pWideBuff, nWideCount);

	std::wstring strResult = pWideBuff;
	delete pWideBuff;
	return strResult;
}