字符集转换(UTF-8、ANSI)
我是因为数据库使用时,有中文所以导致需要转字符集
UTF-8字符集转ANSI字符集
CString MachinePara::Utf82Ansi(CString& srcCode)
{
int srcCodeLen=0;
//计算接收到待转换字符串的缓冲区所需宽字符数
srcCodeLen=MultiByteToWideChar(CP_UTF8,NULL,srcCode,srcCode.GetLength(),NULL,0);
wchar_t* result_t=new wchar_t[srcCodeLen+1];
//向result_t缓冲区写入宽字符
MultiByteToWideChar(CP_UTF8,NULL,srcCode,srcCode.GetLength(),result_t,srcCodeLen);
result_t[srcCodeLen]='\0';
//计算接收到待转换字符串的缓冲区所需字节数
srcCodeLen=WideCharToMultiByte(CP_ACP,NULL,result_t,wcslen(result_t),NULL,0,NULL,NULL);
char* result=new char[srcCodeLen+1];
//向result缓冲区写入字符
WideCharToMultiByte(CP_ACP,NULL,result_t,wcslen(result_t),result,srcCodeLen,NULL,NULL);
result[srcCodeLen]='\0';
CString srcAnsiCode;
srcAnsiCode=result;
delete []result_t;
delete []result;
return srcAnsiCode;
}
ANSI字符集转UTF-8字符集
CString MachinePara::ANSItoUTF8(CString& strAnsi)
{
//获取转换为宽字节后需要的缓存区大小,创建宽字节缓存区,936为简体中文GB2312代码页
UINT nLen = MultiByteToWideChar(936, NULL, strAnsi, -1, NULL, NULL);
WCHAR* wszBuffer = new WCHAR[nLen + 1];
nLen = MultiByteToWideChar(936, NULL, strAnsi, -1, wszBuffer, nLen);
wszBuffer[nLen] = 0;
//获取转为UTF8多字节后需要的缓存区大小 创建多字节缓存区
nLen = WideCharToMultiByte(CP_UTF8, NULL, wszBuffer, -1, NULL, NULL, NULL, NULL);
CHAR* szBuffer = new CHAR[nLen + 1];
nLen = WideCharToMultiByte(CP_UTF8, NULL, wszBuffer, -1, szBuffer, nLen, NULL, NULL);
szBuffer[nLen] = 0;
strAnsi = szBuffer;
//内存清理
delete[]wszBuffer;
delete[]szBuffer;
return strAnsi;
}