码迷,mamicode.com
首页 > 其他好文 > 详细

宽字节UTF-8、多字节互转

时间:2018-08-27 18:41:02      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:new   转换   宽字节   not   不同   多字节   class   code   ons   

  在进行Windows编程时,常常遇到不同字符编码之间的转换以对应不同的输出格式,本文介绍宽字节UTF-8编码格式和多字节之间的项目转换。分别调用Windows底层函数MultiByteToWideChar和  WideCharToMultiByte实现。

1.UTF-8转多字节

  

std::string u82mb(const char* cont)
{
    if (NULL == cont)
    {
        return "";
    }

    int num = MultiByteToWideChar(CP_UTF8, NULL, cont, -1, NULL, NULL);
    if (num <= 0)
    {
        return "";
    }
    wchar_t* buffw = new (std::nothrow) wchar_t[num];
    if (NULL == buffw)
    {
        return "";
    }
    MultiByteToWideChar(CP_UTF8, NULL, cont, -1, buffw, num);
    int len = WideCharToMultiByte(CP_ACP, 0, buffw, num - 1, NULL, NULL, NULL, NULL);
    if (len <= 0)
    {
        delete[] buffw;
        return "";
    }
    char* lpsz = new (std::nothrow) char[len + 1]; 
    if (NULL == lpsz)
    {
        delete[] buffw;
        return "";
    }
    WideCharToMultiByte(CP_ACP, 0, buffw, num - 1, lpsz, len, NULL, NULL);
    lpsz[len]=\0;
    delete[] buffw;
    std::string rtn(lpsz);
    delete[] lpsz;
    return rtn;
}

2.多字节转UTF-8

std::string mb2u8(const char* cont)
{
    if (NULL == cont)
    {
        return "";
    }
    int num = MultiByteToWideChar(CP_ACP, NULL, cont, -1, NULL, NULL);
    if (num <= 0)
    {
        return "";
    }
    wchar_t* buffw = new (std::nothrow) wchar_t[num];
    if (NULL == buffw)
    {
        return "";
    }
    MultiByteToWideChar(CP_ACP, NULL, cont, -1, buffw, num);
    int len = WideCharToMultiByte(CP_UTF8, 0, buffw, num - 1, NULL, NULL, NULL, NULL); 
    if (len <= 0)
    {
        delete[] buffw;
        return "";
    }
    char* lpsz = new (std::nothrow) char[len + 1]; 
    if (NULL == lpsz)
    {
        delete[] buffw;
        return "";
    }
    WideCharToMultiByte(CP_UTF8, 0, buffw, num - 1, lpsz, len, NULL, NULL);
    lpsz[len]=\0;
    delete[] buffw;
    std::string rtn(lpsz);
    delete[] lpsz;
    return rtn ;
}

 

宽字节UTF-8、多字节互转

标签:new   转换   宽字节   not   不同   多字节   class   code   ons   

原文地址:https://www.cnblogs.com/wanlu/p/9542839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!