简化wince中字符串ansi与unicode相互转化的函数

//从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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值