天天看点

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