本地编码(GBK,GB2312等)转unicode 再转UTF-8 的C++代码

如下是一段本地编码到unicode以及utf-8编码的转换代码.是基于STL 的string类的.使用了windows的API :

MultiByteToWideChar和WideCharToMultiByte.故它只能在windows平台下使用.

这里没有针对超长的字符串转换作优化,不能保证转换大段数据时的效率.

 

#include <string>

#include <windows.h>

 

 

// 其它辅助函数:编码转换

static std::wstring mb2wc(const std::string  &strC,UINT CodePage= CP_ACP);

static std::string  wc2mb(const std::wstring &strW,UINT CodePage= CP_ACP);

using namespace std;

 

wstring mb2wc(const string &strC,UINT CodePage)

{

    const int strlen = strC.size();

    int nNeedSize = MultiByteToWideChar(CodePage,0,strC.c_str(),strlen,NULL,0);

    if(nNeedSize<=0)

        return wstring();

    wchar_t *pWChar = new wchar_t[nNeedSize+1];

    int nRetSize = MultiByteToWideChar(CodePage,0,strC.c_str(),strlen,pWChar,nNeedSize);

    if(nRetSize<=0){

        delete[] pWChar;

        return wstring();

    }

    wstring  ss(pWChar,nRetSize);

    delete[] pWChar;

    return ss;

}

 

string wc2mb(const wstring &strW,UINT CodePage)

{

    const int strlen = strW.size();

    int nNeedSize = WideCharToMultiByte(CodePage,0,strW.c_str(),strlen,NULL,0,NULL,NULL);

    if(nNeedSize<=0)

        return string();

    char *pStr = new char[nNeedSize+1];

    int nRetSize = WideCharToMultiByte(CodePage,0,strW.c_str(),strlen,pStr,nNeedSize,NULL,NULL);

    if(nRetSize<=0){

        delete[] pStr;

        return string();

    }

    string  ss(pStr,nRetSize);

    delete[] pStr;

    return ss;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值