字符编码转换实现(基于windows接口)

调用接口说明:

MultiByteToWideChar function (stringapiset.h) - Win32 apps | Microsoft Learn

WideCharToMultiByte function (stringapiset.h) - Win32 apps | Microsoft Learn

代码示例:

#include <windows.h>
#include <string>
#include <stdio.h>
#include <iostream>

bool UTF8ToWide(std::wstring& wstr, const std::string& utf8)
{
    int size = MultiByteToWideChar(CP_UTF8, NULL, utf8.c_str(), utf8.size(), NULL, NULL);
    wchar_t* wide = new wchar_t[size];
    wmemset(wide, L'\0', size);
    size = MultiByteToWideChar(CP_UTF8, NULL, utf8.c_str(), utf8.size(), wide, size);
    wstr.assign(wide, size);
    delete[] wide;
    wide = NULL;

    return true;
}

bool ANSIToWide(std::wstring& wstr, const std::string& ansi)
{
    int size = MultiByteToWideChar(CP_ACP, NULL, ansi.c_str(), ansi.size(), NULL, NULL);
    wchar_t* wide = new wchar_t[size];
    wmemset(wide, L'\0', size);
    size = MultiByteToWideChar(CP_ACP, NULL, ansi.c_str(), ansi.size(), wide, size);
    wstr.assign(wide, size);
    delete[] wide;
    wide = NULL;

    return true;
}

bool WideToUTF8(std::string& utf8, const std::wstring& wstr)
{
    int size = WideCharToMultiByte(CP_UTF8, NULL, wstr.c_str(), wstr.size(), NULL, NULL, NULL, NULL);
    char* utf8_buf = new char[size];
    memset(utf8_buf, '\0', size);
    size = WideCharToMultiByte(CP_UTF8, NULL, wstr.c_str(), wstr.size(), utf8_buf, size, NULL, NULL);
    utf8.assign(utf8_buf, size);
    delete[] utf8_buf;
    utf8_buf = NULL;

    return true;
}

bool WideToANSI(std::string& ansi, const std::wstring& wstr)
{
    int size = WideCharToMultiByte(CP_ACP, NULL, wstr.c_str(), wstr.size(), NULL, NULL, NULL, NULL);
    char* ansi_buf = new char[size];
    memset(ansi_buf, '\0', size);
    size = WideCharToMultiByte(CP_ACP, NULL, wstr.c_str(), wstr.size(), ansi_buf, size, NULL, NULL);
    ansi.assign(ansi_buf, size);
    delete[] ansi_buf;
    ansi_buf = NULL;

    return true;
}

bool ANSIToUTF8(std::string& utf8, const std::string& ansi)
{
    std::wstring wstr;
    ANSIToWide(wstr, ansi);
    WideToUTF8(utf8, wstr);
    return true;
}

bool UTF8ToANSI(std::string& ansi, const std::string& utf8)
{
    std::wstring wstr;
    UTF8ToWide(wstr, utf8);
    WideToUTF8(ansi, wstr);
    return true;
}

int main()
{
    std::string ansi = "中国";    //  GB2312
    std::string utf8;
    std::wstring wstr_by_ansi;
    std::wstring wstr_by_utf8;
    ANSIToUTF8(utf8, ansi);
    ANSIToWide(wstr_by_ansi, ansi);
    UTF8ToWide(wstr_by_utf8, utf8);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值