gpt4 book ai didi

c++ - 如何在 C/C++ 中将字符串从 UTF8 转换为 Latin1?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:47 25 4
gpt4 key购买 nike

我的问题很简单,但我至今找不到解决方案:

如何在 C++ 中将 UTF8 编码的 string 转换为 latin1 编码的 string 而无需使用任何额外的库(如 libiconv)?

到目前为止我能找到的每个示例都是针对 latin1 到 UTF8 的转换?

最佳答案

typedef unsigned value_type;

template <typename Iterator>
size_t get_length (Iterator p)
{
unsigned char c = static_cast<unsigned char> (*p);
if (c < 0x80) return 1;
else if (!(c & 0x20)) return 2;
else if (!(c & 0x10)) return 3;
else if (!(c & 0x08)) return 4;
else if (!(c & 0x04)) return 5;
else return 6;
}

template <typename Iterator>
value_type get_value (Iterator p)
{
size_t len = get_length (p);

if (len == 1)
return *p;

value_type res = static_cast<unsigned char> (
*p & (0xff >> (len + 1)))
<< ((len - 1) * 6);

for (--len; len; --len)
res |= (static_cast<unsigned char> (*(++p)) - 0x80) << ((len - 1) * 6);

return res;
}

此函数将返回 p 处的 unicode 代码点。您现在可以使用

转换字符串
for (std::string::iterator p = s_utf8.begin(); p != s_utf8.end(); ++p)
{
value_type value = get_value<std::string::iterator&>(p));
if (value > 0xff)
throw "AAAAAH!";
s_latin1.append(static_cast<char>(value));
}

没有保证,代码很旧:)

关于c++ - 如何在 C/C++ 中将字符串从 UTF8 转换为 Latin1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12855643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com