[C/C++]_[Unicode(char*)转UTF8]
1.这里只是单个unicode字符的转换,字符串转换的话需要遍历整个字符串,可用std::string的append添加.
2.如果只是2字节宽的unicode,只需要unicode_char_length = 2就行了。
3.如有问题,请指出.
[cpp]
void OneUnicode2UTF8(const char* unicode_char,size_t unicode_char_length,
char* utf_char)
{
//unicode: 0x192->110010010 ,utf8:0xC692->1100011010010010
int value = 0;
memcpy(&value,unicode_char,unicode_char_length);
if (value >= 0x0000 && value <= 0x007F)
{
utf_char[0] = unicode_char[0];
}
else if (value >= 0x0080 && value <= 0x07FF)
{
utf_char[0] = ((value >> 6) | 0xC0);
utf_char[1] = ((value & 0x3F) | 0x80);
}
else if (value >= 0x0800 && value <= 0xFFFF)
{
utf_char[0] = ((value >> 12) | 0xE0);
utf_char[1] = ((value >> 6 & 0x3F) | 0x80);
utf_char[2] = ((value & 0x3F) | 0x80);
} www.zzzyk.com
else if (value >= 0x10000 && value <= 0x10FFFF)
{
utf_char[0] = (value >> 18 | 0xF0);
utf_char[1] = ((value >> 12 & 0x3F) | 0x80);
utf_char[2] = ((value >> 6 & 0x3F) | 0x80);
utf_char[3] = ((value & 0x3F) | 0x80);
}
else
{
cerr << "value too big." << endl;
assert(0);
}
}
补充:软件开发 , C++ ,