欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-05 14:32:20
在进行Windows编程时,常常遇到不同字符编码之间的转换以对应不同的输出格式,本文介绍宽字节UTF-8编码格式和多字节之间的项目转换。分别调用Windows底层函数MultiByteToWideChar和 WideCharToMultiByte实现。 1.UTF-8转多字节 2.多字节转UTF-8 ......

  在进行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 ;
}