When I program on wince or windows mobile platform, Character encoding constantly bother me. Sometimes, I need disply multibyte character set (not string) on UNICODE platform and Using MultiByteToWideChar can't build a wide string directly. Sometimes, I need save a wide string to file using ANIS without '\0' and Using WideCharToMultiByte can't build a multibyte character set directly, too. So, I write the below code to convert different encoding and different types(set and string) freely.
int ToWideString( WCHAR* &pwStr, const char* pStr, int len, BOOL IsEnd)
{
ASSERT_POINTER(pStr, char);
ASSERT(len >= 0 || len == -1);
int nWideLen = MultiByteToWideChar(CP_ACP, 0, pStr, len, NULL, 0);
if (len == -1)
{
--nWideLen;
}
if (nWideLen == 0)
{
return 0;
}
if (IsEnd)
{
pwStr = new WCHAR[(nWideLen+1)*sizeof(WCHAR)];
ZeroMemory(pwStr, (nWideLen+1)*sizeof(WCHAR));
}
else
{
pwStr = new WCHAR[nWideLen*sizeof(WCHAR)];
ZeroMemory(pwStr, nWideLen*sizeof(WCHAR));
}
MultiByteToWideChar(CP_ACP, 0, pStr, len, pwStr, nWideLen);
return nWideLen;
}
int ToMultiBytes( char* &pStr, const WCHAR* pwStr, int len, BOOL IsEnd)
{
ASSERT_POINTER(pwStr, WCHAR) ;
ASSERT( len >= 0 || len == -1 ) ;
int nChars = WideCharToMultiByte(CP_ACP, 0, pwStr, len, NULL, 0, NULL, NULL);
if (len == -1)
{
--nChars;
}
if (nChars == 0)
{
return 0;
}
if(IsEnd)
{
pStr = new char[nChars+1];
ZeroMemory(pStr, nChars+1);
}
else
{
pStr = new char[nChars];
ZeroMemory(pStr, nChars);
}
WideCharToMultiByte(CP_ACP, 0, pwStr, len, pStr, nChars, NULL, NULL);
return nChars;
}
How to Use
char *pStr = "test";
WCHAR* pwStr;
int nWideLen = ToWideString(pwStr, pStr, -1, TRUE);
WCHAR* pwStr = _T("test");
char *pStr;
int nWideLen = ToMultiBytes(pStr, pwStr, -1, TRUE);