您的位置:首页 > 编程语言 > C语言/C++

[C/C++]_[utf8和unicode的相互转换]

2013-10-05 16:28 393 查看
场景:

1.有些库需要接收utf8字符串(也比如数据库表数据),而路径处理则需要unicode字符串,所有在windows下互相转换是必须的。

2.之前自己实现了utf8转unicode,但是并不完美,因为超过4字节的utf8字符串或big endian的字节序支持不好,所以在windows最好的方式应该就是使用系统接口了.

#include "windows.h"

char* QXUtf82Unicode(const char* utf, size_t *unicode_number)
{
if(!utf || !strlen(utf))
{
*unicode_number = 0;
return NULL;
}
int dwUnicodeLen = MultiByteToWideChar(CP_UTF8,0,utf,-1,NULL,0);
size_t num = dwUnicodeLen*sizeof(wchar_t);
wchar_t *pwText = (wchar_t*)malloc(num);
memset(pwText,0,num);
MultiByteToWideChar(CP_UTF8,0,utf,-1,pwText,dwUnicodeLen);
*unicode_number = dwUnicodeLen - 1;
return (char*)pwText;
}

char* QXUnicode2Utf8(const char* unicode)
{
int len;
len = WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)unicode, -1, NULL, 0, NULL, NULL);
char *szUtf8 = (char*)malloc(len + 1);
memset(szUtf8, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)unicode, -1, szUtf8, len, NULL,NULL);
return szUtf8;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: