多位元組與寬位元組
阿新 • • 發佈:2018-12-30
多位元組是指使用多個位元組(1-3)表示一個字元。比如gbk使用英文佔一個位元組,中文佔2個,這個就是多位元組了。
寬位元組一般是固定使用2個位元組表示一個字元,utf-16(一般就是指unicode)。
//將多位元組char*轉化為寬位元組wchar_t*
wchar_t* AnsiToUnicode( const char* szStr )
{
//計算需要多少個寬位元組才能表示對應的多位元組字串
int nLen = MultiByteToWideChar( CP_ACP, 0, szStr, -1, NULL, 0 );
if (nLen == 0)
{
return NULL;
}
wchar_t* pResult = new wchar_t[nLen];
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );
return pResult;
}
//將寬位元組wchar_t*轉化為多位元組char*
char* UnicodeToAnsi( const wchar_t* szStr )
{
int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );
if (nLen == 0)
{
return NULL;
}
char* pResult = new char[nLen];
WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );
return pResult;
}