编码转换问题

#include 
#include 
#include 
#include 
/**
 * 中文字串转为utf8格式字串
 * src  中文字串
 * ret  utf8字串
 * len  src串的长度
 * 返回转换后的utf8串的长度
 * 说明:ret大小应该是src的1.5倍以上。一个汉字转为了3个字节的utf编码
 **/
int To_utf8(unsigned char *src,unsigned char *ret,int len){
	iconv_t c_p;
	char *in,*out;
	int i,i_len,o_len;
	unsigned char tmp[1500];
	memset(tmp,0,sizeof(tmp));
	c_p=iconv_open("UTF-8","GBK"); //GBK 转为 UTF-8
	in=(char *)src;out=(char *)tmp;
	i_len=len;o_len=1500;
	iconv(c_p,&in,(size_t*)&i_len,&out,(size_t*)&o_len);
	i=strlen((char *)tmp);
	memcpy(ret,tmp,i);
	iconv_close(c_p);
	return i;
}
 
/**
 * utf8格式字串转为中文字串
 * src  utf8字串
 * ret  中文字串
 * len  src串的长度
 * 返回转换后的中文串的长度
 **/
int To_gbk(unsigned char *src,unsigned char *ret,int len){
	iconv_t c_p;
	char *in,*out;
	int i,i_len,o_len;
	unsigned char tmp[1500];
	memset(tmp,0,sizeof(tmp));
	c_p=iconv_open("GBK","UTF-8"); //UTF-8转为 GBK 
	in=(char *)src;out=(char *)tmp;
	i_len=len;o_len=1500;
	iconv(c_p,&in,(size_t*)&i_len,&out,(size_t*)&o_len);
	i=strlen((char *)tmp);
	memcpy(ret,tmp,i);
	iconv_close(c_p);
	return i;
}

//string 转utf8 windows环境
#include
std::string string_To_UTF8(const std::string& str)
{
	int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
	wchar_t* pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴 
	ZeroMemory(pwBuf, nwLen * 2 + 2);
	::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);
	int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
	char* pBuf = new char[nLen + 1];
	ZeroMemory(pBuf, nLen + 1);
	::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
	std::string retStr(pBuf);
	delete[]pwBuf;
	delete[]pBuf;
	pwBuf = NULL;
	pBuf = NULL;
	return retStr;
}


 

你可能感兴趣的:(编码转换问题)