你或许会认为这很容易获得,但我很难找到一个简单的库函数,可以将C或C++字符串从ISO-8859-1编码转换为UTF-8。 我正在读取以8位ISO-8859-1编码的数据,但需要将其转换为UTF-8字符串以在SQLite数据库和最终的Android应用程序中使用。
我找到了一个商业产品,但目前超出我的预算范围。
我找到了一个商业产品,但目前超出我的预算范围。
如果你的源编码将始终为ISO-8859-1,那么这很简单。下面是一个循环:
unsigned char *in, *out;
while (*in)
if (*in<128) *out++=*in++;
else *out++=0xc2+(*in>0xbf), *out++=(*in++&0x3f)+0x80;
为了安全起见,您需要确保输出缓冲区的大小是输入缓冲区的两倍,否则在循环条件中包含大小限制并检查它。
我使用以下代码来编写C++:
std::string iso_8859_1_to_utf8(std::string &str)
{
string strOut;
for (std::string::iterator it = str.begin(); it != str.end(); ++it)
{
uint8_t ch = *it;
if (ch < 0x80) {
strOut.push_back(ch);
}
else {
strOut.push_back(0xc0 | ch >> 6);
strOut.push_back(0x80 | (ch & 0x3f));
}
}
return strOut;
}
http://www.boost.org/doc/libs/1_49_0/libs/locale/doc/html/charset_handling.html
代码如下:#include <boost/locale.hpp>
std::string utf8_string = boost::locale::conv::to_utf<char>(latin1_string,"Latin1");
C++03标准没有直接转换特定字符集的函数。
根据您的操作系统,您可以在Linux上使用iconv(),在Windows上使用MultiByteToWideChar()等方法。 提供大量字符串转换支持的库是开源的ICU库。
isolat1ToUTF8(unsigned char* out, int *outlen,
const unsigned char* in, int *inlen) {
unsigned char* outstart = out;
const unsigned char* base = in;
const unsigned char* processed = in;
unsigned char* outend = out + *outlen;
const unsigned char* inend;
unsigned int c;
int bits;
inend = in + (*inlen);
while ((in < inend) && (out - outstart + 5 < *outlen)) {
c= *in++;
/* assertion: c is a single UTF-4 value */
if (out >= outend)
break;
if (c < 0x80) { *out++= c; bits= -6; }
else { *out++= ((c >> 6) & 0x1F) | 0xC0; bits= 0; }
for ( ; bits >= 0; bits-= 6) {
if (out >= outend)
break;
*out++= ((c >> bits) & 0x3F) | 0x80;
}
processed = (const unsigned char*) in;
}
*outlen = out - outstart;
*inlen = processed - base;
return(0);
}
我觉得这可能会有帮助!对于我上次被删除的评论,我很抱歉!如果需要的话,我可以给你链接,里面有一个.c文件中的完整解释。我从中得到了这个。干杯!
将ISO-8859-1转换为UTF-8只涉及编码算法,因为ISO-8859-1是Unicode的子集。所以您已经有了Unicode代码点。请查看维基百科上的算法。
C++方面——将其与iostreams集成——要困难得多。
我建议您绕过这座山,而不是试图钻过它或攀登它,也就是实现一个简单的字符串转换器。
祝好运。
char *
,而需要使用 unsigned char *
的情况。更重要的非平凡性在于 UTF-8 的定义,具体来说,您需要拒绝代理码点和超出范围的值。幸运的是,在只需要处理 ISO-8859-1 输入的编码器中不会出现这些问题,但如果您编写了这样一个有限的编码器,很可能会有人在稍后扩展输入范围时误用它而没有添加任何检查。 - R.. GitHub STOP HELPING ICE
stpcpy
会有所帮助,前提是你是那种擅长缓冲区大小的程序员。 - Steve Jessopstpcpy
(即使它现在是标准或正在朝着标准的方向发展...?)对于1字节和2字节的复制来说,开销非常大。你最好手动始终复制2个字节,并包含一些代码以跳过第二个指针的推进,如果复制的字节为0,则几乎可以肯定是无分支的。 - R.. GitHub STOP HELPING ICE