我想知道是否有推荐的“跨”Windows 和 Linux 方法用于将字符串从 UTF-16LE 转换为 UTF-8?还是应该为每种环境使用不同的方法?
我设法在谷歌上搜索了一些对 'iconv' 的引用,但出于某种原因,我找不到基本转换的示例,例如 - 将 wchar_t UTF-16 转换为 UTF-8。
任何人都可以推荐一种“交叉”的方法,如果您知道参考资料或样本指南,将不胜感激。
谢谢, 多里酒吧
使用 PowerShell 将编码更改为 UTF-8:
Get-Content PATH\temp.txt -Encoding Unicode | Set-Content -Encoding UTF8 PATH2\temp.txt
如果你不想使用ICU,
开源ICU库非常常用。
#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);
我也遇到了这个问题,我通过使用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 缓冲区。
如果您安装了 MSYS2,则该iconv
软件包(默认安装)允许您使用:
iconv -f utf-16le -t utf-8 <input.txt >output.txt
还有utfcpp,它是一个仅限标头的库。
在 UTF-8、UTF-16、UTF-32、wchar 之间转换字符串的另一种可移植 C 可能性是mdz_unicode库。
谢谢大家,这就是我设法解决“交叉”窗口和 linux 要求的方法:
MinGW
和MSYS
libiconv
源码包libiconv
通过编译MSYS
。就是这样。