天天看點

windows C++ gbk轉為utf-8

1、在windows下可以使用函數MultiByteToWideChar先将多位元組字元,轉換為unicode。

2、使用函數WideCharToMultiByte,将unicode再轉換為utf8編碼。

google一下,網上例子很多。在這裡貼了一個簡單的源碼,實作ansi到utf8編碼的轉換

char *multichar_2_utf8(const char *m_string)
{
	int len=0;
	wchar_t *w_string;
	char *utf8_string;
    //計算由ansi轉換為unicode後,unicode編碼的長度
	len=multibytetowidechar(cp_acp,0,(lpctstr)m_string, -1, null,0);//cp_acp訓示了轉換為unicode編碼的編碼類型
	w_string=(wchar_t *)malloc(2*len+2);
	memset(w_string,0,2*len+2);
    //ansi到unicode轉換
	multibytetowidechar(cp_acp, 0, (lpctstr)m_string,-1,w_string, len);//cp_acp訓示了轉換為unicode編碼的編碼類型
    //計算unicode轉換為utf8後,utf8編碼的長度
	len = widechartomultibyte(cp_utf8, 0, w_string, -1, null, 0, null, null);//cp_utf8訓示了unicode轉換為的類型
    	utf8_string=(char  *)malloc(len+1);
    	memset(utf8_string, 0, len + 1);
    //unicode到utf8轉換
    	widechartomultibyte (cp_utf8, 0, w_string, -1, utf8_string, len, null,null);//cp_utf8訓示了unicode轉換為的類型
	free(w_string);
	return utf8_string;
}