ANSII 与Unicode,Utf8之间的转换

  在项目开发中,我们难免会遇到各种问题,特别是字符直接的转换,这里列举字符直间转换的代码:

  

using namespace std;

wstring AnsiiToUnicode(const string& str) {
    // 参数的长度
    int strLen = str.length();
    // 预算-缓冲区中宽字节的长度
    int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
    // 给指向缓冲区的指针变量分配内存
    allocator<wchar_t> wc_t;
    wchar_t *pUnicode = wc_t.allocate(sizeof(wchar_t)*(unicodeLen+1),0);
    // 开始向缓冲区转换字节
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, unicodeLen);
    wstring ret_str = pUnicode;
    delete pUnicode;
    return ret_str;
}
string UnicodeToAssii(const wstring& wstr) {
    // 参数的长度
    int wstrLen = wstr.length();
    // 预算-缓冲区中多字节的长度
    int ansiiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0,nullptr,nullptr);
    // 给指向缓冲区的指针变量分配内存
    allocator<char> c_t;
    char *pAssii = c_t.allocate(sizeof(char)*(ansiiLen + 1), 0);
    // 开始向缓冲区转换字节
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, pAssii, ansiiLen,nullptr,nullptr);
    string ret_str = pAssii;
    delete pAssii;
    return ret_str;
}
wstring Utf8ToUnicode(const string& str) {
    // 参数的长度
    int strLen = str.length();
    // 预算-缓冲区中宽字节的长度
    int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
    // 给指向缓冲区的指针变量分配内存
    allocator<wchar_t> wc_t;
    wchar_t *pUnicode = wc_t.allocate(sizeof(wchar_t)*(unicodeLen + 1), 0);
    // 开始向缓冲区转换字节
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, pUnicode, unicodeLen);
    wstring ret_str = pUnicode;
    delete pUnicode;
    return ret_str;
}
string UnicodeToUtf8(const wstring& wstr) {
    // 参数的长度
    int wstrLen = wstr.length();
    // 预算-缓冲区中多字节的长度
    int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
    // 给指向缓冲区的指针变量分配内存
    allocator<char> c_t;
    char *pAssii = c_t.allocate(sizeof(char)*(ansiiLen + 1), 0);
    // 开始向缓冲区转换字节
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);
    string ret_str = pAssii;
    delete pAssii;
    return ret_str;
}
string AnsiiToUtf8(const string& str) {
    return UnicodeToUtf8(AnsiiToUnicode(str));
}

 源贴地址:http://tieba.baidu.com/p/4381031865

转载于:https://www.cnblogs.com/happinessday/p/6277478.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值