//从unicode字符串转换成dbcs字符串需要多少字节
size_t GetT2AStringByteCount(LPCTSTR lpszInput);
//从dbcs字符串转换成unicode字符串需要多少字节
size_t GetA2TStringByteCount(LPCSTR lpszInput);
//转换unicode字符串到dbcs字符串
void T2AString(LPCTSTR lpszInput,LPSTR lpszOutput);
//转换dbcs字符串到unicode字符串
void A2TString(LPCSTR lpszInput,LPTSTR lpszOutput);
size_t GetT2AStringByteCount(LPCTSTR lpszInput)
{
return WideCharToMultiByte( //计算从Unicode转换到Ansi后需要的字节数
CP_ACP, //根据ANSI code page转换
WC_COMPOSITECHECK|WC_SEPCHARS/*WC_DEFAULTCHAR*/, //转换出错用缺省字符代替
lpszInput, //要转换的字符串地址
-1/*nTCHARNum*/, //要转换的个数
0, //转换后字符串放置的地址
0, //最多转换字符的个数,为0表示返回转换Unicode后需要多少个字节
0, //缺省的字符:"/0"
0 //缺省的设置
);
}
size_t GetA2TStringByteCount(LPCSTR lpszInput)
{
return 2*MultiByteToWideChar( //计算从Ansi转换到Unicode后需要的字节数
CP_ACP,
MB_PRECOMPOSED/*MB_COMPOSITE*/,
lpszInput, //要转换的Ansi字符串
-1, //自动计算长度
0,
0
);
}
void T2AString(LPCTSTR lpszInput,LPSTR lpszOutput)
{
int nCharNum=GetT2AStringByteCount(lpszInput);
WideCharToMultiByte(
CP_ACP,
WC_COMPOSITECHECK|WC_DEFAULTCHAR,
lpszInput,
-1/*nTCHARNum*/,
lpszOutput,
nCharNum,
0,
0);
}
void A2TString(LPCSTR lpszInput,LPTSTR lpszOutput)
{
int nTCHARNum=GetA2TStringByteCount(lpszInput);
MultiByteToWideChar(
CP_ACP,
MB_COMPOSITE,
lpszInput,
-1,
lpszOutput,
nTCHARNum/2);
}
使用示例
void CStrtestDlg::OnButton1()
{
// TODO: Add your control notification handler code here
LPTSTR lpszInput=_T("你好hello");
int nCount= GetT2AStringByteCount(lpszInput);
TRACE(_T("%d/n"),nCount );
LPSTR lpszOutput=new char[nCount+1];
memset(lpszOutput,0,nCount+1);
T2AString(lpszInput,lpszOutput);
for(int i=0 ;i<= nCount ; ++i)
TRACE(_T("%c"),*(lpszOutput+i) );
TRACE(_T("/n"));
delete [] lpszOutput;
}
void CStrtestDlg::OnButton2()
{
// TODO: Add your control notification handler code here
LPSTR lpszInput="hello你好";
int nCount=GetA2TStringByteCount(lpszInput);
TRACE(_T("%d/n"),nCount );
LPTSTR lpszOutput=new TCHAR[nCount/2];
memset(lpszOutput,0,nCount);
A2TString(lpszInput,lpszOutput);
TRACE(_T("%s/n"),lpszOutput );
delete [] lpszOutput;
}