zoukankan      html  css  js  c++  java
  • utf8、ansii、unicode编码之间的转换

    #include "stdafx.h"
    #include "windows.h"
    #include <iostream>
    #include <string>
    #include <memory>

    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));
    }
    string Utf8ToAnsii(const string& str) {
    return UnicodeToAssii(Utf8ToUnicode(str));
    }

  • 相关阅读:
    angularjs学习之六(angularjs中directive指令的一般编程事件绑定 模板使用等)
    Flex 容器基本概念
    flex 4 布局样式
    flex 特效
    delphi ehLib 安装包下载及安装方法
    CnPack IDE 专家包(CnWizards)显示代引用单元列表
    Delphi 获取DataSet传入参数后的SQL命令
    偶写的第一个控件,一个用选择代替输入的Edit控件…
    delphi中响应鼠标进入或离开控件的方法
    Delphi常用关键字用法详解
  • 原文地址:https://www.cnblogs.com/HemJohn/p/7494323.html
Copyright © 2011-2022 走看看