// CodeTranse.cpp : Defines the entry point for the console
application.
//
#ifdef WIN32
#include
#else
#include
#endif
#include
#include
#include
#include
//#include
using namespace std;
#ifdef WIN32
//GB2312到UTF-8的转换
char* G2U(const char* gb2312)
{
int len = MultiByteToWideChar(CP_ACP, 0, gb2312,
-1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr,
len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1,
NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str,
len, NULL, NULL);
if(wstr) delete[] wstr;
return str;
}
//UTF-8到GB2312的转换
char* U2G(const char* utf8)
{//windows
int len = MultiByteToWideChar(CP_UTF8, 0, utf8,
-1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr,
len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1,
NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str,
len, NULL, NULL);
if(wstr) delete[] wstr;
return str;
}
#else
//==linux
int code_convert(char *from_charset,char *to_charset,char
*inbuf,size_t inlen,char *outbuf,size_t outlen)
{
iconv_t cd;
int rc;
char **pin = &inbuf;
char **pout = &outbuf;
cd = iconv_open(to_charset,from_charset);
if (cd==0)
return -1;
memset(outbuf,0,outlen);
if (iconv(cd,pin,&inlen,pout,
&outlen)==-1)
return -1;
iconv_close(cd);
return 0;
}
//UNICODE码转为GB2312码
int u2g(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("utf-8","gb2312", inbuf,
inlen, outbuf, outlen);
}
//GB2312码转为UNICODE码
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
return code_convert("gb2312","utf-8", inbuf,
inlen, outbuf, outlen);
}
#endif
//==end linux
char* URLDecode(char* URL)
{
char*
pDecode =URL;
char*
pURL =URL;
while('\0'!=(*pDecode=*pURL))
{
++pURL;
if('%'==*pDecode)
{
*pDecode=(*pURL>='A'?(*pURL-'A'+10):(*pURL-'0'));
++pURL;
*pDecode=(*pDecode<<=4)|(*pURL>='A'?(*pURL-'A'+10):(*pURL-'0'));
++pURL;
}
++pDecode;
}
return
URL;
}
char* CodeTranse(char* s)
{
char* str = URLDecode(s);
#ifdef WIN32
return U2G(str);
#else
char *p = new char[200];
memset(p, 0, 200);
u2g(str,strlen(str), p,
200); return p;
#endif
}
int main(int argc, char* argv[])
{
// “中国”这两个字在 baidu
中的编码是�й� 为 gb2312 编码后转成 16 进制
//在 google 中的编码是 中国 为 utf-8 编码后转成 16
进制 char str[100] = {0};
strcpy(str, "abc123他妈的,我靠");
char *desStr = CodeTranse(str);
printf("%s\n", desStr);
int a;
scanf("%d", &a);
return 0;
}