ansi utf8 unicode 三者之间相互转换
作者:互联网
转载地址:https://www.jianshu.com/p/1d54f59f8785
1 #include <iostream> 2 #include <string> 3 #include <fstream> 4 5 using std::string; 6 using namespace std; 7 8 wchar_t* AnsiToUnicode(char *sAnsi) 9 { 10 11 //ansi to unicode 12 int sLen = MultiByteToWideChar(CP_ACP, NULL, sAnsi, -1, NULL, 0); 13 wchar_t* sUnicode = new wchar_t[sLen]; 14 //wchar_t* sUnicode = (wchar_t*)malloc(sLen*sizeof(wchar_t)); 15 MultiByteToWideChar(CP_ACP, NULL, sAnsi, -1, sUnicode, sLen); 16 17 18 return sUnicode; 19 //delete[] sUnicode; 20 //sUnicode =NULL; 21 //free(sUnicode); 22 } 23 24 char *UnicodeToUtf8(wchar_t *sUnicode) 25 { 26 int sLen = WideCharToMultiByte(CP_UTF8, NULL, sUnicode, -1, NULL, 0, NULL, NULL); 27 //UTF8虽然是Unicode的压缩形式,但也是多字节字符串,所以可以以char的形式保存 28 char* sUtf8 = new char[sLen]; 29 //unicode版对应的strlen是wcslen 30 WideCharToMultiByte(CP_UTF8, NULL, sUnicode, -1, sUtf8, sLen, NULL, NULL); 31 printf(""); 32 return sUtf8; 33 /*delete[] sUtf8; 34 sUtf8 =NULL; */ 35 } 36 37 38 //ansi转换为utf-8 39 char *AnsiToUtf8(char *sAnsi){ 40 wchar_t *unicode = AnsiToUnicode(sAnsi); 41 free(sAnsi); 42 43 if(unicode != NULL){ 44 /*setlocale(LC_ALL,"chs"); 45 wprintf(L"%s\n",unicode);*/ 46 47 char *utf_8 = UnicodeToUtf8(unicode); 48 if(utf_8){ 49 free(unicode); 50 return utf_8; 51 } 52 else{ 53 free(unicode); 54 return NULL; 55 } 56 }else 57 return NULL; 58 59 }
标签:sLen,utf8,char,ansi,sUnicode,unicode,wchar,NULL 来源: https://www.cnblogs.com/wllwqdeai/p/14691088.html