32

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

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

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

谢谢, 多里酒吧

4

9 回答 9

12

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

Get-Content PATH\temp.txt -Encoding Unicode | Set-Content -Encoding UTF8 PATH2\temp.txt
于 2015-03-11T08:46:14.017 回答
6

如果你不想使用ICU,

  1. Windows:WideCharToMultiByte
  2. Linux:iconv (Glibc)
于 2010-05-20T02:08:29.263 回答
5

开源ICU库非常常用。

于 2010-05-19T18:57:35.653 回答
5
#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);
于 2010-05-20T02:03:16.763 回答
4

我也遇到了这个问题,我通过使用boost locale 库来解决它

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-16LE 编码的缓冲区转换UTF-8 转 ANSI,确保编码正确(这里我使用的是 Latin-1,ISO-8859-1 的编码)。

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

于 2013-12-04T04:37:29.383 回答
4

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

 iconv -f utf-16le -t utf-8 <input.txt >output.txt
于 2020-04-03T10:26:06.670 回答
2

还有utfcpp,它是一个仅限标头的库。

于 2012-10-12T17:19:23.353 回答
1

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

于 2021-03-10T14:16:07.167 回答
0

谢谢大家,这就是我设法解决“交叉”窗口和 linux 要求的方法:

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

就是这样。

于 2010-05-20T12:36:44.513 回答