C++编码转换多字节字符宽字符

int UnicodeToGB2312(char **dest, const WCHAR *src)
{
	char* buffer;
	int size = ::WideCharToMultiByte(CP_ACP, 0, src, -1, NULL, 0, NULL, NULL);  
	// null termidated wchar''s buffer
	buffer = new char[size];
	int ret = ::WideCharToMultiByte(CP_ACP, NULL, src, -1, buffer, size + 1, NULL, NULL);

	if (*dest != 0)
		delete *dest;
	*dest = buffer;

	return ret;
}


int Gb2312ToUnicode(WCHAR **dest, const char *src)
{
	int length = strlen(src);                // null terminated buffer
	WCHAR *buffer = new WCHAR[length + 1];   // WCHAR means unsinged short, 2 bytes
                                           // provide enough buffer size for Unicodes

	int ret = ::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, src, length, buffer, length);
	buffer[ret] = 0;

	if (*dest != 0)
		delete *dest;
	*dest = buffer;

	return ret;
}


std::string & Utf8ToAnsi(std::string &scr, std::string &des)
{
	size_t n = scr.size()*2;
	wchar_t *sl = new wchar_t[n];
 
	char *sm = new char[n];
	//多字节(UTF8)编码转换为宽字节编码
	MultiByteToWideChar(CP_UTF8,0,scr.c_str(),-1,sl,n);
 
	//宽字节转换为多字节(Ansi)编码
	WideCharToMultiByte(CP_ACP, 0,sl, -1,sm, n,NULL,0);
 
	des = sm;
	delete []sl;
	delete []sm;
 
	return des;
}
 
//Ansi编码转换为Unicode(Utf16)编码
std::wstring & AnsiToUtf16(std::string &scr, std::wstring &des)
{
	size_t n = scr.size();
 
	wchar_t *sl = new wchar_t[n+1];
 
	MultiByteToWideChar(CP_ACP,0,scr.c_str(),-1,sl,n+1);
 
	des = sl;
	delete []sl;
 
	return des;
}

你可能感兴趣的:(C++,编码转换,宽字符,多字节字符)