A-A+

GBK转UTF8编码-UTF8转GBK编码(C++)

2014年09月13日 C++知识 评论 1 条 阅读 1,256 次

版本一:string,GBK转UTF8,UTF8转GBK

#include <iostream>
#include "tchar.h"
#include <string>
#include <windows.h> 
using namespace std;

string GBKToUTF8(const std::string & strGBK)
{
	string strOutUTF8 = "";
	WCHAR * str1;
	int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
	str1 = new WCHAR[n];
	MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
	n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
	char * str2 = new char[n];
	WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
	strOutUTF8 = str2;
	delete[]str1;
	str1 = NULL;
	delete[]str2;
	str2 = NULL;
	return strOutUTF8;
}

string UTF8ToGBK(const std::string & strUTF8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0);
	unsigned short * wszGBK = new unsigned short[len + 1];
	memset(wszGBK, 0, len * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUTF8.c_str(), -1, wszGBK, len);
	len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
	char *szGBK = new char[len + 1];
	memset(szGBK, 0, len + 1);
	WideCharToMultiByte(CP_ACP,0, wszGBK, -1, szGBK, len, NULL, NULL);
	//strUTF8 = szGBK;
	std::string strTemp(szGBK);
	delete[]szGBK;
	delete[]wszGBK;
	return strTemp;
}

int _tmain(int argc, _TCHAR * argv[])
{
	string test = "C/C++程序员之家 - 关注cplusplus,关注互联网,关注路由与交换.程序员的历程.";
	cout<<test<<endl;
	cout<<GBKToUTF8(test)<<endl; //转为UTF8
	cout<<UTF8ToGBK(GBKToUTF8(test))<<endl; //转为UTF8再转为GBK
	return 0;
}

版本二:CString,GBK转UTF8,UTF8转GBK

CString UTF8ToGB(CString & str)
{
	CString szOut;
    WCHAR *strSrc;
    TCHAR *szRes;
    int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
    strSrc = new WCHAR[i+1];
    MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
    i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
    szRes = new TCHAR[i+1];
    WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
    szOut = szRes;
    delete []strSrc;
    delete []szRes;
	return szOut;
}  

CString GBKToUTF8(CString & strGBK)
{
	CString strOutUTF8 = "";
	WCHAR * str1;
	int n = MultiByteToWideChar(CP_ACP, 0, strGBK, -1, NULL, 0);
	str1 = new WCHAR[n];
	MultiByteToWideChar(CP_ACP, 0, strGBK, -1, str1, n);
	n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
	char * str2 = new char[n];
	WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
	strOutUTF8 = str2;
	delete[]str1;
	str1 = NULL;
	delete[]str2;
	str2 = NULL;
	return strOutUTF8;
}

Copyright:www.cplusplus.me Share、Open- C/C++程序员之家

标签:

1 条留言  访客:1 条  博主:0 条

  1. 广*位

    感觉C++,和JAVA代码有点相似。。。

给我留言

Copyright © C/C++程序员之家 保留所有权利.   Theme  Ality 浙ICP备15011757号-3

用户登录