在visual studio项目中,进行Unicode字符集和多字节字符集转换

        在实际开发中,有可能项目是多字节字符集的,但是要处理的一些网络数据是Unicode字符集的(比如http消息,有时使用的是utf8字符编码,那就使用的是Unicode字符集了)。这时候,就需要进行Unicode字符集和多字节字符集转换了。

        下面提供的参考是使用WindowsAPI实现的。

1.utf8字符编码数据 --> Ansi字符编码数据

#include <windows.h>
#include <shlwapi.h>

std::string Utf8ToAnsi(std::string str)
{
    // 将string中的 utf-8数据 转存到wstring
    int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
    std::wstring utf8Str(size - 1, L'\0');
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &utf8Str[0], size);

    // 将wstring中的 utf-8数据转为ANSI数据 存到string
    size = WideCharToMultiByte(CP_ACP, 0, utf8Str.c_str(), -1, nullptr, 0, nullptr, nullptr);
    std::string gbkStr = std::string(size - 1, '\0');
    WideCharToMultiByte(CP_ACP, 0, utf8Str.c_str(), -1, &gbkStr[0], size, nullptr, nullptr);

    return gbkStr;
}

2.Ansi字符编码数据 --> utf8字符编码数据

#include <windows.h>
#include <shlwapi.h>

std::string AnsiToUtf8(std::string str)
{
    // 将string中的 ANSI编码数据转utf-8 转存到wstring
    int size = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
    std::wstring ansiStr(size - 1, L'\0');
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &ansiStr[0], size);

    // 将wstring中的 utf-8编码数据 存到string
    size = WideCharToMultiByte(CP_UTF8, 0, ansiStr.c_str(), -1, nullptr, 0, nullptr, nullptr);
    std::string utf8Str = std::string(size - 1, '\0');
    WideCharToMultiByte(CP_UTF8, 0, ansiStr.c_str(), -1, &utf8Str[0], size, nullptr, nullptr);

    return utf8Str;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值