Unicode 多字节 utf-8互转

BOOL achr2wchr( const char *src, wchar_t *dst, int dst_len )
{
 size_t len = strlen(src);
 size_t wlen = MultiByteToWideChar(CP_ACP, 0, (const char*)src, int(len), NULL, 0);
 if (wlen > dst_len)
 {
  return FALSE;
 }
 MultiByteToWideChar(CP_ACP, 0, (const char*)src, int(len), (wchar_t*)dst, int(wlen));
 return TRUE;
}
BOOL wch2ach( const wchar_t* src, char *dst, int dst_len )
{
 size_t wlen = wcslen(src);
 size_t len = WideCharToMultiByte(CP_OEMCP, NULL, (const wchar_t*)src, int(wlen), NULL, 0, NULL, FALSE);
 if (len > dst_len)
 {
  return FALSE;
 }
 WideCharToMultiByte(CP_OEMCP, NULL, (const wchar_t*)src, int(wlen), (char*)dst, int(len), NULL, FALSE);
 return TRUE;
}
// 多字节编码转为UTF8编码  
bool MBToUTF8(char* pu8, const char* pmb, int u_len) 
{  
 // convert an MBCS string to widechar   
 int nLen = MultiByteToWideChar(CP_ACP, 0, pmb, -1, NULL, 0); 
 WCHAR* lpszW = NULL;  
 try  
 {  
  lpszW = new WCHAR[nLen];  
 }  
 catch(bad_alloc &memExp)  
 {  
  return false;  
 } 
 int nRtn = MultiByteToWideChar(CP_ACP, 0, pmb, -1, lpszW, nLen); 
 if(nRtn != nLen)  
 {  
  delete[] lpszW;  
  return false;  
 }  
 // convert an widechar string to utf8  
 int utf8Len = WideCharToMultiByte(CP_UTF8, 0, lpszW, -1, NULL, 0, NULL, NULL);  
 if (utf8Len <= 0
  || u_len < utf8Len)  
 { 
  delete[] lpszW;  
  return false;  
 }  
 nRtn = WideCharToMultiByte(CP_UTF8, 0, lpszW, nLen, pu8, utf8Len, NULL, NULL);  
 delete[] lpszW; 
 return true;  
} 
// UTF8编码转为多字节编码  
bool UTF8ToMB(char* pmb, const char* pu8, int b_len)  
{
 int nLen = MultiByteToWideChar( CP_UTF8, 0, pu8, -1, NULL, NULL );//得到UTF8编码的字符串长度,是2
 LPWSTR lpwsz = new WCHAR[nLen];
 MultiByteToWideChar( CP_UTF8, 0, pu8, -1, lpwsz, nLen );//转换的结果是UCS2格式的价值两个字
 int nLen1 = WideCharToMultiByte( CP_ACP, 0, lpwsz, nLen, NULL, NULL, NULL, NULL );
 if (b_len < nLen1)
 {
  return false;
 }
 WideCharToMultiByte( CP_ACP, 0, lpwsz, nLen, pmb, nLen1, NULL, NULL );//转换完毕
 delete [] lpwsz;
 return true;  
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值