urlEncoder

拷贝自php的源码,url编码

 1 //url decode
 2 //str:输入,输出
 3 //len:str输入字符串大小
 4 //返回值:str解码后字符串大小
 5 int php_url_decode(char *str, int len);
 6 
 7 //url encode 
 8 //out:用户分配内存,大小len*3+1,保障0结尾
 9 //返回值:编码后字符串大小,不包含null
10 int php_url_encode(char const *s, int len, char *out);
 1 #include "urlEncoder.h"
 2 
 3 #include <ctype.h>
 4 
 5 //////////////////////////////////////////////////////////////////////////
 6 //url encode decode
 7 static unsigned char hexchars[] = "0123456789ABCDEF";
 8 
 9 int php_htoi(char *s)
10 {
11     int value;
12     int c;
13 
14     c = ((unsigned char *)s)[0];
15     if (isupper(c))
16         c = tolower(c);
17     value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16;
18 
19     c = ((unsigned char *)s)[1];
20     if (isupper(c))
21         c = tolower(c);
22     value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10;
23 
24     return (value);
25 }
26 
27 
28 int php_url_encode(char const *s, int len, char *out)
29 {
30     register unsigned char c;
31     unsigned char *to, *start;
32     unsigned char const *from, *end;
33 
34     from = (unsigned char *)s;
35     end  = (unsigned char *)s + len;
36     start = to = (unsigned char*)out;//(unsigned char *) calloc(1, 3*len+1);
37 
38     while (from < end) 
39     {
40         c = *from++;
41 
42         if (c == ' ') 
43         {
44             *to++ = '+';
45         } 
46         else if ((c < '0' && c != '-' && c != '.') ||
47             (c < 'A' && c > '9') ||
48             (c > 'Z' && c < 'a' && c != '_') ||
49             (c > 'z')) 
50         {
51             to[0] = '%';
52             to[1] = hexchars[c >> 4];
53             to[2] = hexchars[c & 15];
54             to += 3;
55         }
56         else 
57         {
58             *to++ = c;
59         }
60     }
61     *to = 0;
62 
63     return to - start;
64 }
65 
66 int php_url_decode(char *str, int len)
67 {
68     char *dest = str;
69     char *data = str;
70 
71     while (len--) 
72     {
73         if (*data == '+') 
74         {
75             *dest = ' ';
76         }
77         else if (*data == '%' && len >= 2 && isxdigit((int) *(data + 1)) && 
78             isxdigit((int) *(data + 2))) 
79         {
80             *dest = (char) php_htoi(data + 1);
81             data += 2;
82             len -= 2;
83         } 
84         else 
85         {
86             *dest = *data;
87         }
88         data++;
89         dest++;
90     }
91     *dest = '/0';
92     return dest - str;
93 }
94 //end url encode decode
95 //////////////////////////////////////////////////////////////////////////

猜你喜欢

转载自www.cnblogs.com/blogbobo/p/10595419.html