【问题标题】:Convert UTF-16 to UTF-8 under Windows and Linux, in C在 Windows 和 Linux 下,在 C 中将 UTF-16 转换为 UTF-8
【发布时间】:2011-02-21 11:12:15
【问题描述】:

我想知道是否有推荐的“跨”Windows 和 Linux 方法用于将字符串从 UTF-16LE 转换为 UTF-8?还是应该为每种环境使用不同的方法?

我已经设法在谷歌上搜索了一些对 'iconv' 的引用,但出于某种原因,我找不到基本转换的示例,例如 - 将 wchar_t UTF-16 转换为 UTF-8。

任何人都可以推荐一种“交叉”的方法,如果您知道参考资料或样本指南,将不胜感激。

谢谢,Doori 酒吧

【问题讨论】:

标签: c unicode utf-8 utf-16


【解决方案1】:

使用 PowerShell 将编码更改为 UTF-8:

Get-Content PATH\temp.txt -Encoding Unicode | Set-Content -Encoding UTF8 PATH2\temp.txt

【讨论】:

  • 在 Windows 2008 R2 上运行良好。还添加了 BOM。
【解决方案2】:

如果你不想使用ICU,

  1. 窗口:WideCharToMultiByte
  2. Linux:iconv (Glibc)

【讨论】:

    【解决方案3】:

    开源的ICU library很常用。

    【讨论】:

      【解决方案4】:
      #include <iconv.h>
      
      wchar_t *src = ...; // or char16_t* on non-Windows platforms
      int srclen = ...;
      char *dst = ...;
      int dstlen = ...;
      iconv_t conv = iconv_open("UTF-8", "UTF-16");
      iconv(conv, (char*)&src, &srclen, &dst, &dstlen);
      iconv_close(conv);
      

      【讨论】:

      • 我想“UTF-16”和“UTF-8”应该互换位置。
      • iconv... 从何而来?答案:#include – 此外,这似乎是特定于 Linux 的。
      • libiconv 是一个跨平台库,可在包括 Linux 在内的许多平台上使用。
      【解决方案5】:

      我也遇到过这个问题,我用boost locale library解决了

      try
      {           
          std::string utf8 = boost::locale::conv::utf_to_utf<char, short>(
                              (short*)wcontent.c_str(), 
                              (short*)(wcontent.c_str() + wcontent.length()));
          content = boost::locale::conv::from_utf(utf8, "ISO-8859-1");
      }
      catch (boost::locale::conv::conversion_error e)
      {
          std::cout << "Fail to convert from UTF-8 to " << toEncoding << "!" << std::endl;
          break;
      }
      

      boost::locale::conv::utf_to_utf 函数尝试将 UTF-16LE 编码的缓冲区转换为 UTF-8, boost::locale::conv::from_utf 函数尝试将 UTF-8 编码的缓冲区转换为 ANSI,确保编码正确(这里我使用 Latin-1 编码, ISO-8859-1)。

      另外提醒一下,在 Linux 中 std::wstring 是 4 个字节长,但在 Windows 中 std::wstring 是 2 个字节长,所以最好不要使用 std::wstring 来包含 UTF-16LE 缓冲区。

      【讨论】:

        【解决方案6】:

        如果您安装了 MSYS2,那么 iconv 软件包(默认安装)允许您使用:

         iconv -f utf-16le -t utf-8 <input.txt >output.txt
        

        【讨论】:

          【解决方案7】:

          还有utfcpp,它是一个只有头文件的库。

          【讨论】:

            【解决方案8】:

            在 UTF-8、UTF-16、UTF-32、wchar 之间转换字符串的另一种可移植 C 可能性是 mdz_unicode 库。

            【讨论】:

              【解决方案9】:

              谢谢大家,这就是我设法解决“跨”windows 和 linux 要求的方法:

              1. 已下载并安装:MinGWMSYS
              2. 下载libiconv源码包
              3. 通过MSYS编译libiconv

              就是这样。

              【讨论】:

                猜你喜欢
                • 2015-09-21
                • 2019-11-29
                • 2011-09-06
                • 2015-09-19
                • 1970-01-01
                • 2017-09-24
                • 1970-01-01
                相关资源
                最近更新 更多