首页 > 代码库 > 自己写unicode转换ascii码,wchar*到char*

自己写unicode转换ascii码,wchar*到char*

对于ascii码的char其实就是unicode码wchar的首个字节码,

如wchar[20] = "qqqq"; 在内存中排码其实是char的‘q‘ ‘\0‘这类,因此我们如果自己写unicode码转换为ascii的char,只需要取其首字节即可,如下本人写了一个wchar到char的转换的函数。由于代码简单,加上了内存泄露测试方式。

 

#include <stdio.h>
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <tchar.h>
#include <Windows.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

char* UnicodeToMultibyte(WCHAR *wStr)
{

	if (NULL != wStr)
	{
		int nLen = wcslen(wStr);
		char *pStr = new char[nLen + 1];
		int i = 0;
		for (; i < nLen; ++i)
		{
			(pStr)[i] = (char)*(wStr + i);
		}
		(pStr)[i] = '\0';
		printf("%s\n", pStr);
		return pStr;
	}
	return NULL;
}
int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	/*char *str = new char[100];*/
	WCHAR wStr[250] = L"qqqqqqqqqqqqq";
	char szTemp[250] = _T("wwwwwwwwwwwww");
	char* pTemp = UnicodeToMultibyte(wStr);
	strcpy(szTemp, pTemp);
	delete pTemp;		//注意,小心内存泄露
	printf("%s\n", szTemp);

	return 0;

}


当然也可以通过windows的转换函数,这个msdn上有详解就不解释啦

 

char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn)  
{  
	LPSTR pszOut = NULL;  
	if (lpwszStrIn != NULL)  
	{  
		int nInputStrLen = wcslen (lpwszStrIn);  

		// Double NULL Termination  
		int nOutputStrLen = WideCharToMultiByte (CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;  
		pszOut = new char [nOutputStrLen];  

		if (pszOut)  
		{  
			memset (pszOut, 0x00, nOutputStrLen);  
			WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);  
		}  
	}  
	return pszOut;  
}


 

自己写unicode转换ascii码,wchar*到char*