linux C++ Utf8toGb2312 Gb2312toUtf8 MyA2W和MyW2A实现

CHealper.h

#ifndef __CHELPER_H__
#define __CHELPER_H__
#include <string>

int Utf8toGb2312(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen);

int Gb2312toUtf8(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen);

std::wstring MyA2W(std::string buf);

std::string MyW2A(std::wstring buf);

#endif

CHealper.cpp

#include <stdio.h>
#include <iconv.h>
#include <string.h>
#include <stdlib.h>
#include "CHelper.h"
using namespace std;

int Utf8toGb2312(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen) {

	iconv_t cd;
	if ((cd = iconv_open("gb2312", "utf-8")) == 0)
		return -1;

	memset(destbuf, 0, *destlen);
	char **source = (char**)&sourcebuf;
	char **dest = &destbuf;
	if (-1 == iconv(cd, source, &sourcelen, dest, destlen))
		return -1;

	iconv_close(cd);
	return 0;
}

int Gb2312toUtf8(const char *sourcebuf, size_t sourcelen, char *destbuf, size_t* destlen) {

	iconv_t cd;
	if ((cd = iconv_open("utf-8", "gb2312")) == 0)
		return -1;

	memset(destbuf, 0, *destlen);
	char **source = (char**)&sourcebuf;
	char **dest = &destbuf;
	if (-1 == iconv(cd, source, &sourcelen, dest, destlen))
		return -1;

	iconv_close(cd);
	return 0;
}
/************************************************************************/
/*   string to wstring                                                  */
/************************************************************************/
std::wstring MyA2W(std::string strBuf) 
{
	std::wstring strValue = L"";

	if (strBuf.length() <= 0)
		return strValue;
	setlocale(LC_CTYPE, "zh_CN.utf8");

	size_t nDestLen = mbstowcs(nullptr, strBuf.c_str(), 0) + 1;
	if (nDestLen == size_t(-1) )
		return strValue;

	wchar_t* pBuf = nullptr;
	pBuf = new wchar_t[nDestLen];
	if (!pBuf)
		return strValue;

	mbstowcs(pBuf, strBuf.c_str(), nDestLen);

	strValue = pBuf;
	if (pBuf)
		delete [] pBuf, pBuf = nullptr;

	return strValue;
}

/************************************************************************/
/*	  wstring to string                                                 */
/************************************************************************/
std::string MyW2A(std::wstring strBuf) 
{
	std::string strValue = "";

	if (strBuf.length() <= 0)
		return strValue;

	size_t nSize = strBuf.length() * sizeof(strBuf[0]);
	char* pBuf = nullptr;
	pBuf = new char[nSize];
	if (!pBuf)
		return strValue;

	size_t nDestLen = wcstombs(pBuf, strBuf.c_str(), nSize);
	if (nDestLen == size_t(0))
		return strValue;

	strValue = pBuf;
	if (pBuf)
		delete[] pBuf, pBuf = nullptr;

	return strValue;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值