【MFC】UTF-8与Unicode编码转换

本文介绍了一个在MFC环境下实现UTF-8与Unicode编码相互转换的函数。该函数利用多字节字符集进行操作,通过MultiByteToWideChar和WideCharToMultiByte函数完成编码转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境

适用范围:MFC。

字符集:多字节字符集。

 

声明

CString             UTF8AndUnicode_Convert(CString &strSource, UINT nSourceCodePage, UINT nTargetCodePage);

 

定义

CString UTF8AndUnicode_Convert(CString &strSource, UINT nSourceCodePage, UINT nTargetCodePage)
{
    CString        strTarget; 
	
    wchar_t        *pWideBuf;
    int            nWideBufLen;
	
    char           *pMultiBuf;
    int            nMiltiBufLen;

    int            nSourceLen;

    nSourceLen = strSource.GetLength(); 
    nWideBufLen = MultiByteToWideChar(nSourceCodePage, 0, strSource, -1, NULL, 0); 
	
    pWideBuf = new wchar_t[nWideBufLen+1]; 
    memset(pWideBuf, 0, (nWideBufLen + 1) * sizeof(wchar_t)); 
	
    MultiByteToWideChar(nSourceCodePage, 0, strSource, -1, (LPWSTR)pWideBuf, nWideBufLen);

    pMultiBuf = NULL;
    nMiltiBufLen = WideCharToMultiByte(nTargetCodePage, 0, (LPWSTR)pWideBuf, -1, (char *)pMultiBuf, 0, NULL, NULL); 
	
    pMultiBuf = new char[nMiltiBufLen+1]; 
    memset(pMultiBuf, 0, nMiltiBufLen + 1); 

    WideCharToMultiByte(nTargetCodePage, 0, (LPWSTR)pWideBuf, -1, (char *)pMultiBuf, nMiltiBufLen, NULL, NULL); 
	
    strTarget.Format(_T("%s"), pMultiBuf); 
	
    delete pWideBuf; 
    delete pMultiBuf; 
	
    return strTarget; 
}

 

调用方法

UTF-8转Unicode

m_strUnicode = UTF8AndUnicode_Convert(m_strUTF8, CP_UTF8, CP_ACP);

Unicode转UTF-8

m_strUTF8 = UTF8AndUnicode_Convert(m_strUnicode, CP_ACP, CP_UTF8);

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值