ansi utf8 unicode 三者之间相互转换
1、 ANSI->UTF8
转载地址: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 }
2、UTF8->ANSI
来源:https://blog.csdn.net/baidu_41793719/article/details/104316708
1 wchar_t *utf_8ToUnicode(char *u8s) 2 { 3 int wcsLen = MultiByteToWideChar(CP_UTF8, NULL, u8s, strlen(u8s), NULL, NULL); 4 wchar_t *wcString = new wchar_t[wcsLen + 1]; 5 MultiByteToWideChar(CP_UTF8, NULL, u8s, strlen(u8s), wcString, wcsLen); 6 wcString[wcsLen] = '\0'; 7 return wcString; 8 } 9 10 char *unicodeToAnsi(wchar_t *wcString) 11 { 12 int len = WideCharToMultiByte(CP_ACP, NULL, wcString, -1, NULL, NULL, NULL, NULL); 13 char *str = new char[len]; 14 WideCharToMultiByte(CP_ACP, NULL, wcString, -1, str, len, NULL, NULL); 15 return str; 16 } 17 18 char* UTF8ToAnsi(char* u8s) 19 { 20 wchar_t* pW = utf_8ToUnicode(u8s); 21 return unicodeToAnsi(pW); 22 delete pW; 23 }