转码utf8 - unicode 和 unicode - utf8

本文提供了一种在UTF-8编码与Unicode编码之间进行相互转换的方法。通过两个C++函数实现:一个是将UTF-8字符串转换为Unicode宽字符字符串,另一个是将Unicode宽字符字符串转换回UTF-8字符串。这些函数可用于解决不同编码环境下的文本处理问题。
wchar_t *UTF8ToUnicode(const char* pu8, int utf8Len)
{
    int nLen = MultiByteToWideChar(CP_UTF8, 0, pu8, utf8Len, NULL, 0);
    if (nLen <=0)
    {
        return NULL;
	}
	wchar_t *uncode;
	uncode = new wchar_t[nLen+1];
	int nRtn = MultiByteToWideChar(CP_UTF8, 0, pu8, utf8Len, uncode, nLen);
	if(nRtn != nLen)
	{
		delete []uncode;
        return NULL;
	}
	uncode[nLen]=0;
    return uncode;
}
char* UnicodeToUTF8(wchar_t* pun, int uLen)
{
    // convert an widechar string to utf8
	int utf8Len = WideCharToMultiByte(CP_UTF8, 0, pun, uLen, NULL, 0, NULL, NULL);
	if (utf8Len<=0)
    {
        return NULL;
	}
	char *pu8;
	pu8 = new char[utf8Len+1];
    int nRtn = WideCharToMultiByte(CP_UTF8, 0, pun, uLen, pu8, utf8Len, NULL, NULL);
    if (nRtn != utf8Len)
    {
		delete []pu8;
        return NULL;
	}
	pu8[utf8Len]=0;
    return pu8;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值