Windows下常用的几种字符转换

//CString转UTF8编码
char* ConvertCStringW2UTF8(CStringW &instr,char *date)
{ 
    memset(date,0,strlen(date));
    wchar_t * wstr = instr.GetBuffer();
    int ulen = ::WideCharToMultiByte(CP_UTF8, NULL, wstr, wcslen(wstr), NULL, NULL, NULL, NULL);
    WideCharToMultiByte(CP_UTF8, NULL, wstr, -1, date, ulen, NULL, NULL);    
    date[ulen+1] = '\0';
    instr.ReleaseBuffer();//释放    
    return date;
}

//UTF8编码字符转
CStringCStringW ConvertUTF82CStringW(char* instr)
{    
    CStringW wstr;    
    int wlen = MultiByteToWideChar(CP_UTF8,NULL,instr,strlen(instr), NULL, NULL);
    wchar_t* wstrnew = new wchar_t[wlen+1];    
    memset(wstrnew,0,sizeof(wchar_t)*(wlen+1));    
    MultiByteToWideChar(CP_UTF8,NULL, instr, -1, wstrnew,wlen);    
    wstrnew[wlen] = '\0';    
    wstr.SetString(wstrnew); 
    delete[] wstrnew; 
    wstrnew = NULL;    
    return wstr;
}

//int转CString
CString ConvertInt2CString(int indata)
{ 
    CString str; 
    str.Format(_T("%d"),indata); 
    return str;
}

//CString转int
int ConvertCString2Int(CString &instr)
{ 
    return _ttoi(instr);
}

//CString转float
float ConvertCString2Float(CString &instr)
{ 
    return (float)_ttof(instr);
}

//Unicode下字符转CString
CString ConvertChar2CString(char *instr)
{ 
    CString str; 
    str.Format(_T("%s"),instr); 
    return str;
}

//float转CString
CString Convertfloat2CString(float indata)
{ 
    CString str; 
    str.Format(_T("%.1lf"),indata); 
    return str;
}

//ASCII编码转CString
CStringW ConvertANSI2CStringW(char* buf, int ulen)
{
    wchar_t* pUnicode; 
    pUnicode = new wchar_t[ulen+1];  //转换长度为ulen个UNICODE字符长度 
    memset(pUnicode,0,(ulen+1)*sizeof(wchar_t)); 
    MultiByteToWideChar(CP_ACP,0,buf,-1,(LPWSTR)pUnicode,ulen); 
    pUnicode[ulen] = '\0'; 
    CStringW wstr = pUnicode; 
    delete[] pUnicode; 
    pUnicode = NULL;    
    return wstr;
}

//CString转ASCII编码字符
char *ConvertCStringW2ANSI(CString &instr, char *buf)
{ 
    WideCharToMultiByte(CP_ACP,0,instr.GetBuffer(),-1,(LPSTR)buf,instr.GetLength()*2+1,NULL,NULL); 
    instr.ReleaseBuffer(); 
    return buf;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值