windows平台下的字符串编码转换函数(C++实现)

#include <windows.h>

\\原理:利用MultiByteToWideChar和WideCharToMultiByte将原来的字符转成unicode再转成目标字符集

string Convert(string str, int sourceCodepage, int targetCodepage)      \\str 要转换的字符串 sourceCodepage 原编码方式 targetCodepage 目标编码方式
{     
     size_t len=str.length();     
     size_t unicodeLen=MultiByteToWideChar(sourceCodepage,0,str.c_str(),-1,NULL,0);       
       
     wchar_t* pUnicode = NULL;     
     pUnicode=new wchar_t[unicodeLen+1];       
     memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));       
     MultiByteToWideChar(sourceCodepage,0,str.c_str(),-1,(LPWSTR)pUnicode,(int)unicodeLen);       
       
     BYTE* pTargetData = NULL;       
     int targetLen=WideCharToMultiByte(targetCodepage,0,(LPWSTR)pUnicode,-1,     
                                       (char *)pTargetData,0,NULL,NULL);       
     pTargetData=new BYTE[targetLen+1];       
     memset(pTargetData,0,targetLen+1);       
                   
     WideCharToMultiByte(targetCodepage,0,(LPWSTR)pUnicode,-1,     
                         (char*)pTargetData,targetLen,NULL,NULL);       
     string rt((char*)pTargetData);        
                   
     delete [] pUnicode;       
     delete [] pTargetData;       
     return rt;       
}  

 

编码方式:

CP_ACP:ANSI;CP_MACCP:Macintosh;CP_OEMCP:OEM;

CP_SYMBOL:符号代码页(42);CP_THREAD_ACP:当前线程ANSI代码页;

CP_UTF7:UTF-7;CP_UTF8:UTF-8。

936:GBK

声明:如未作说明,则本文为 渣滓洞【解旻的博客】 原创。转载务必注明出处
注意:转载须保留全文,如需修改请联系作者

本文永久地址:http://xieminis.me/?p=145