[转载] GB2312和UTF8转换,URLencode,C++,windows

 1 //UTF-8到GB2312的转换
 2 char* U2G(const char* utf8)
 3 {
 4     int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
 5     wchar_t* wstr = new wchar_t[len+1];
 6     memset(wstr, 0, len+1);
 7     MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
 8     len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
 9     char* str = new char[len+1];
10     memset(str, 0, len+1);
11     WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
12     if(wstr) delete[] wstr;
13         return str;
14 }
15  
16 //GB2312到UTF-8的转换
17 char* G2U(const char* gb2312)
18 {
19     int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0);
20     wchar_t* wstr = new wchar_t[len+1];
21     memset(wstr, 0, len+1);
22     MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len);
23     len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
24     char* str = new char[len+1];
25     memset(str, 0, len+1);
26     WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
27     if(wstr) delete[] wstr;
28         return str;
29 }        

转自CSDN

URLencode,URLdecode, C++,windows,转自http://blog.csdn.net/gemo/article/details/8468311:

 1 unsigned char ToHex(unsigned char x) 
 2 { 
 3   return x > 9 ? x + 55 : x + 48; 
 4 }
 5 
 6 unsigned char FromHex(unsigned char x) 
 7 { 
 8   unsigned char y;
 9   if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;
10   else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;
11   else if (x >= '0' && x <= '9') y = x - '0';
12   else assert(0);
13   return y;
14 }
15 
16 std::string UrlEncode(const std::string& str)
17 {
18   std::string strTemp = "";
19   size_t length = str.length();
20   for (size_t i = 0; i < length; i++)
21   {
22     if (isalnum((unsigned char)str[i]) || 
23       (str[i] == '-') ||
24       (str[i] == '_') || 
25       (str[i] == '.') || 
26       (str[i] == '~'))
27       strTemp += str[i];
28     else if (str[i] == ' ')
29       strTemp += "+";
30     else
31     {
32       strTemp += '%';
33       strTemp += ToHex((unsigned char)str[i] >> 4);
34       strTemp += ToHex((unsigned char)str[i] % 16);
35     }
36   }
37   return strTemp;
38 }
39 
40 std::string UrlDecode(const std::string& str)
41 {
42   std::string strTemp = "";
43   size_t length = str.length();
44   for (size_t i = 0; i < length; i++)
45   {
46     if (str[i] == '+') strTemp += ' ';
47     else if (str[i] == '%')
48     {
49       assert(i + 2 < length);
50       unsigned char high = FromHex((unsigned char)str[++i]);
51       unsigned char low = FromHex((unsigned char)str[++i]);
52       strTemp += high*16 + low;
53     }
54     else strTemp += str[i];
55   }
56   return strTemp;
57 }

 

posted on 2015-04-22 14:43  记不住  阅读(325)  评论(0编辑  收藏  举报

导航