矮人村

标题: url解码 [打印本页]

作者: kingojie    时间: 2017-9-3 22:02
标题: url解码
/* 16进制字符表 */
static const char c2x_table[] = "0123456789ABCDEF";
/* 字符转16进制 */
static unsigned char *c2x(unsigned what,unsigned char *where)
{
*where++ = '%';
*where++ = c2x_table[what>>4];
*where++ = c2x_table[what&0xf];
return where;
}
/* 16进制转字符 */
static char x2c(const char *what)
{
register char digit;
digit = ((what[0] >= 'A') ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
digit *= 16;
digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
return (digit);
}
/*
%^[]`+$,@:;/!#?=&.
不安全字符及特殊字符
*/
static int unsafechar(unsigned char ch)
{
unsigned char *p=&ch;
if(*p==' '||*p==''||*p=='%'||*p==''||*p=='^'||*p=='['||*p==']'||*p=='`'
||*p=='+'||*p=='$'||*p==','||*p=='@'||*p==':'||*p==';'
||*p=='/'||*p=='!'||*p=='#'||*p=='?'||*p=='='||*p=='&'||*p=='.'||*p>0x80){
return(1);
}
else{
return(0);
}
}
/*
URL解码
*/
size_t url_decode(const char *src,char *dest)
{
char *cp=dest;
while(*src!='')
{
if(*src=='+')
{
*dest++=' ';
}
else if(*src=='%')
{
int ch;
ch=x2c(src+1);
*dest++=ch;
src+=2;
}
else
{
*dest++=*src;
}
src++;
}
*dest='';
return(dest-cp);
}
/*
URL编码
*/
size_t url_encode(const char *src, char *dest)
{
char *cp=dest;
while(*src!='')
{
unsigned char *p=(unsigned char*)src;
if(*p==' '){
*dest++='+';
}
else if(unsafechar(*p))
{
unsigned char w[3]={''};
c2x(*p,w);
*dest=w[0];
*(dest+1)=w[1];
*(dest+2)=w[2];
dest+=3;
}
else
{
*dest++=*p;
}
src++;
}
*dest='';
return(dest-cp);
}
int main()
{
char *s="中国人民@#$%^&*();/@";
char *d=NULL,*d1=NULL;
d=(char *)malloc(100);
d1=(char *)malloc(100);
memset(d,0,100);
memset(d1,0,100);
url_encode(s,d);
printf("%sn",s);
printf("%sn",d);
url_decode(d,d1);
printf("%sn",d1);




欢迎光临 矮人村 (http://airencun.com/) Powered by Discuz! X3.1