• 认真地记录技术中遇到的坑!
  • 能摸鱼真是太好啦!嘿嘿嘿!

UT8与GBK编码互转

C/C++ Moxun 6年前 (2018-06-07) 3984次浏览 0个评论

UTF8-转GBK

#include 
#include "windows.h"
std::string UtfToGbk(const char* utf8)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len + 1];
    memset(wstr, 0, len + 1);
    MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
    len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* str = new char[len + 1];
    memset(str, 0, len + 1);
    WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
    if (wstr)
    {
        delete[] wstr;
        wstr = nullptr;
    }
    std::string strGBK = str;
    delete[]str;
    str = nullptr;
    return strGBK;
}

GBK转UTF8

#include  
#include "windows.h"
std::string ConvertGBKToUtf8(std::string strGb2312)
{
    int nwLen = ::MultiByteToWideChar(CP_ACP, 0, strGb2312.c_str(), -1, NULL, 0);
    wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
    ZeroMemory(pwBuf, nwLen * 2 + 2);
    ::MultiByteToWideChar(CP_ACP, 0, strGb2312.c_str(), strGb2312.length(), pwBuf, nwLen);
    int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
    char * pBuf = new char[nLen + 1];
    ZeroMemory(pBuf, nLen + 1);
    ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
    std::string retStr(pBuf);
    delete[]pwBuf;
    delete[]pBuf;
    pwBuf = NULL;
    pBuf = NULL;
    return retStr;
}

C++中默认的编码格式是GBK,一般网络中传输数据使用的是UTF-8编码格式,至于各种编码格式,回头再仔细了解一下。


转载请注明出处 UT8与GBK编码互转
喜欢 (2)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址