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

Doo*_*Bar 25 c unicode utf-8 utf-16

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

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

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

谢谢,Doori酒吧

Ale*_*x B 6

如果您不想使用ICU,

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


小智 6

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

powershell -Command "Get-Content PATH\temp.txt -Encoding Unicode | Set-Content -Encoding UTF8 PATH2\temp.txt"
Run Code Online (Sandbox Code Playgroud)


M.M*_*M.M 6

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

 iconv -f utf-16le -t utf-8 <input.txt >output.txt
Run Code Online (Sandbox Code Playgroud)


Han*_*ant 5

开源ICU库非常常用.


Rem*_*eau 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);
Run Code Online (Sandbox Code Playgroud)

  • 我想“UTF-16”和“UTF-8”应该互换位置。 (2认同)

小智 5

我也遇到过这个问题,我通过使用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;
}
Run Code Online (Sandbox Code Playgroud)

升压::区域:: CONV :: utf_to_utf功能尝试从由UTF-16LE编码成UTF-8缓冲区转换,该升压::区域:: CONV :: from_utf功能尝试从由一个编码转换缓冲区UTF-8到ANSI,确保编码正确(这里我使用Latin-1编码,ISO-8859-1).

另一个提示是,在Linux中,std :: wstring的长度为4个字节,但在Windows中,std :: wstring的长度为2个字节,因此最好不要使用std :: wstring来包含UTF-16LE缓冲区.


Doo*_*Bar 0

谢谢大家,这就是我如何解决“跨”Windows 和 Linux 需求的方法:

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

就是这样。