在Windows和Linux下,在C中将UTF-16转换为UTF-8

我想知道是否有一个推荐的’交叉’Windows和Linux方法,用于将字符串从UTF-16LE转换为UTF-8? 或者每个环境应该使用不同的方法?

我设法谷歌几个引用’iconv’,但对于somreason我找不到基本转换的样本,例如 – 将wchar_t UTF-16转换为UTF-8。

任何人都可以推荐一种“交叉”的方法,如果您知道参考文献或带样本的指南,我将非常感激。

谢谢,Doori酒吧

如果您不想使用ICU,

  1. Windows: WideCharToMultiByte
  2. Linux: iconv (Glibc)

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

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

开源ICU库非常常用。

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

 try { std::string utf8 = boost::locale::conv::utf_to_utf( (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缓冲区。

 wchar_t *src = ...; 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); 

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

谢谢大家,这就是我设法解决’交叉’窗口和Linux要求:

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

就是这样。