zoukankan      html  css  js  c++  java
  • window下 ANSI Unicode utf8之间相互转换

    //CString to string的转可能只适用于某些编码情况
    string CStringToChar(const CString& strSrc)
    {
      CString strTmp(strSrc);
      string str(strTmp.GetBuffer(strTmp.GetLength()));
      strTmp.ReleaseBuffer();
      return str;
    }

    wstring AnsiToUnicode(const string& buf)
    {
      int len = ::MultiByteToWideChar(CP_ACP, 0, buf.c_str(), -1, NULL, 0);
      if (len == 0) return L"";

      wstring strUnicode;
      strUnicode.resize(len);
      ::MultiByteToWideChar(CP_ACP, 0, buf.c_str(), -1, (wchar_t*)strUnicode.c_str(), len);

      return strUnicode;
    }

    string UnicodeToAnsi(const wstring& buf)
    {
      int len = ::WideCharToMultiByte(CP_ACP, 0, buf.c_str(), -1, NULL, 0, NULL, NULL);
      if (len == 0) return "";

      string strUtf8;
      strUtf8.resize(len);
      ::WideCharToMultiByte(CP_ACP, 0, buf.c_str(), -1, (char*)strUtf8.c_str(), len, NULL, NULL);

      return strUtf8;
    }

    wstring Utf8ToUnicode(const string& buf)
    {
      int len = ::MultiByteToWideChar(CP_UTF8, 0, buf.c_str(), -1, NULL, 0);
      if (len == 0) return L"";

      wstring strUnicode;
      strUnicode.resize(len);
      ::MultiByteToWideChar(CP_UTF8, 0, buf.c_str(), -1, (wchar_t*)strUnicode.c_str(), len);

      return strUnicode;
    }

    string UnicodeToUtf8(const wstring& buf)
    {
      int len = ::WideCharToMultiByte(CP_UTF8, 0, buf.c_str(), -1, NULL, 0, NULL, NULL);
      if (len == 0) return "";

      string strUtf8;
      strUtf8.resize(len);
      ::WideCharToMultiByte(CP_UTF8, 0, buf.c_str(), -1, (char*)strUtf8.c_str(), len, NULL, NULL);

      return strUtf8;
    }

    string AnsiToUtf8(const string& strSrc)
    {
      return UnicodeToUtf8(AnsiToUnicode(strSrc));
    }

    string AnsiToUtf8(const CString& strSrc)
    {
      return UnicodeToUtf8(AnsiToUnicode(CStringToChar(strSrc)));
    }

  • 相关阅读:
    日常学习随笔-数组、单链表、双链表三种形式实现队列结构的基本操作(源码注释)
    代码重构之单元测试
    C# yield return 用法与解析
    MVC学习手册之数据注解与验证
    C#数字图像处理算法学习笔记(三)--图像几何变换
    关于变量名与类名同名问题
    C# 计时器
    C#入门--索引器
    C#入门--字段与属性
    var与dynamic
  • 原文地址:https://www.cnblogs.com/sancong/p/6406340.html
Copyright © 2011-2022 走看看