UTF8/unicode编码互转代码实现

代码实现

#include <windows.h>
 #include <wchar.h>

 int UnicodeToUTF8(wchar_t * wstr, char* str)
 {
     char*     pElementText;
     int    iTextLen;
     // wide char to multi char
         iTextLen = WideCharToMultiByte( CP_UTF8,
                  0,
                  wstr,
                  -1,
                  NULL,
                  0,
                  NULL,
                  NULL );
     pElementText = new char[iTextLen + 1];
     memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );
    WideCharToMultiByte( CP_UTF8,
                  0,
                  wstr,
                  -1,
                  str,
                  iTextLen,
                  NULL,
                  NULL );
    return iTextLen;
}


int UTF8ToUnicode( char* str , wchar_t * wstr)
{
    int unicodeLen = MultiByteToWideChar( CP_UTF8,
                     0,
                     str,
                     -1,
                     NULL,
                     0 ); 
     wchar_t * pUnicode; 
     pUnicode = new wchar_t[unicodeLen+1]; 
     memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t)); 
     MultiByteToWideChar( CP_UTF8,
                  0,
                  str,
                 -1,
                  (LPWSTR)wstr,
                  unicodeLen ); 
     return unicodeLen; 
 }

int main()  
{  
    unsigned char utf8[] = {0xE6,0x9c,0xAA,0xE7,0x9F,0xA5, 0x00};
    wchar_t unicode[256];
    unsigned char utfresult[256];
    UTF8ToUnicode((char*)utf8,unicode);
    UnicodeToUTF8(unicode, (char*)utfresult);
    while(1);
    return 0;  
} 

运行结果:

运行结果

猜你喜欢

转载自blog.csdn.net/imgsq/article/details/51351653