| 项目搜索 |
| |
|
代码片段库:
查看代码片段
浏览
| 提交新的代码片段
| 创建代码包
多字节函数库系列:UTF-8相关:u8towc()
|
类型:
Function |
类别:
Other
|
许可证:
GNU Library Public License |
语言:
C++
|
描述:
将国际通行用于磁盘存储的8bits字节序列——UTF-8编码的字符转换为wchar_t宽字节字符。
|
该代码片段的版本系列:
片段ID |
下载版本 |
提交时间 |
提交人 |
删除 |
4576 | 0.1 | 2002-06-26 21:14 | renxiao | |
点击"下载版本"来下载该代码片段.
最新版本的代码片段: 0.1
/*--------------------------Own_lib函数库系列 u8towc.cc------------------------
cy_u8towc() /u8towc.o /libcyfunc.a
描述: 将国际通行用于磁盘存储的8bits字节序列---UTF-8编码的字符转换为wchar_t宽字
节字符不需要查找码表, 它通过简单的码位截取与合成即可完成.
本函数提供这一实现.
dest_wchar:
保存转换后的宽字节字符目标地址.
src_str:
被转换的UTF-8编码源字符的多字节序列.
返回值:
返回被转换的字符的字节数. 若遇到错误或检测到非法字节序列, 则返回-1.
注意! 传递的字符必须是合法的UTF-8编码序列.
作者: 任逍 |2002.06.06.
版权: GNU General (Library) Public License (GPL/LGPL)
* 编辑器: vim-6.0 |操作系统: TurboLinux7.0简体中文版 *
------------------------------------------------------------------------------*/
#include "cyinclude/cyutf.h"
size_t cy_u8towc(wchar_t dest_wchar, const unsigned char * src_str)
{
int count_bytes = 0;
unsigned char byte_one = 0, byte_other = 0x3f; // 用于位与运算以提取位值
wchar_t tmp_wchar = L'\0';
if (!src_str)
return (size_t)-1;
for (;;) // 检测字节序列长度
{
if (src_str[0] <= 0x7f){
count_bytes = 1; // ASCII字符: 0xxxxxxx( ~ 01111111)
byte_one = 0x7f; // 用于位与运算, 提取有效位值, 下同
break;
}
if ( (src_str[0] >= 0xc0) && (src_str[0] <= 0xdf) ){
count_bytes = 2; // 110xxxxx(110 00000 ~ 110 111111)
byte_one = 0x1f;
break;
}
if ( (src_str[0] >= 0xe0) && (src_str[0] <= 0xef) ){
count_bytes = 3; // 1110xxxx(1110 0000 ~ 1110 1111)
byte_one = 0xf;
break;
}
if ( (src_str[0] >= 0xf0) && (src_str[0] <= 0xf7) ){
count_bytes = 4; // 11110xxx(11110 000 ~ 11110 111)
byte_one = 0x7;
break;
}
if ( (src_str[0] >= 0xf8) && (src_str[0] <= 0xfb) ){
count_bytes = 5; // 111110xx(111110 00 ~ 111110 11)
byte_one = 0x3;
break;
}
if ( (src_str[0] >= 0xfc) && (src_str[0] <= 0xfd) ){
count_bytes = 6; // 1111110x(1111110 0 ~ 1111110 1)
byte_one = 0x1;
break;
}
return (size_t)-1; // 以上皆不满足则为非法序列
}
// 以下几行析取UTF-8编码字符各个字节的有效位值
tmp_wchar = src_str[0] & byte_one;
for (int i=1; i<count_bytes; i++)
{
tmp_wchar <<= 6; // 左移6位后与后续字节的有效位值"位或"赋值
tmp_wchar = tmp_wchar | (src_str[i] & byte_other);
}
// 位值析取__End!
dest_wchar = tmp_wchar;
return count_bytes;
}
如果您修改了一个代码片段并且觉得很应该让别人共享,您可以把这作为这个代码片段的最新版本提交上来. |
|