- #include <stdio.h>
- #include <Windows.h>
- wchar_t * ANSIToUnicode(const char *pANSI)
- {
- wchar_t *pUnicode = NULL;
- int nWideCharLen = 0;
- // step1
- nWideCharLen = MultiByteToWideChar(CP_ACP, 0, pANSI, -1, NULL, 0);
- // step2
- pUnicode = (wchar_t *)malloc(nWideCharLen * sizeof(wchar_t));
- // step3
- MultiByteToWideChar(CP_ACP, 0, pANSI, -1, pUnicode, nWideCharLen * sizeof(wchar_t));
- return pUnicode;
- }
- char * UnicodeToANSI(const wchar_t *pUnicode)
- {
- char *pANSI = NULL;
- int nByte = 0;
- // step1
- nByte = WideCharToMultiByte(CP_ACP, 0, pUnicode, -1, NULL, 0, NULL, NULL);
- // step2
- pANSI = (char *)malloc(nByte);
- // step3
- WideCharToMultiByte(CP_ACP, 0, pUnicode, -1, pANSI, nByte, NULL, NULL);
- return pANSI;
- }
- void fun1()
- {
- char *pANSI = "ANSI to Unicode, ANSI 转换到 Unicode";
- wchar_t *pUnicode = NULL;
- pUnicode = ANSIToUnicode(pANSI);
- if (pUnicode == NULL)
- {
- return;
- }
- MessageBoxW(NULL, pUnicode, TEXT("Unicode"), 0);
- free(pUnicode);
- }
- void fun2()
- {
- wchar_t *pUnicode = TEXT("Unicode to ANSI, Unicode 转换到 ANSI");
- char *pANSI = NULL;
- pANSI = UnicodeToANSI(pUnicode);
- if (pANSI == NULL)
- {
- return;
- }
- MessageBoxA(NULL, pANSI, "ANSI", 0);
- free(pANSI);
- }
- int main()
- {
- // ansi to unicode
- fun1();
- // unicode to ansi
- fun2();
- }
- //该片段来自于http://www.codesnippet.cn/detail/1809201410470.html
来源: http://www.codesnippet.cn/detail/1809201410470.html