url encode decode

来源:互联网 发布:css是什么软件 编辑:程序博客网 时间:2024/05/22 11:35

#define TOHEX(x) ((x)>9 ? (x)+55 : (x)+48)
int URLEncode(string &strIn)
{
 int nInLenth = strIn.length();
 int nFlag = 0;
 BYTE byte;
 char *szOut = new char[nInLenth*3];

 for (int i=0; i<nInLenth; i++){
  byte = strIn[i];
  if (isalnum(byte)){
   szOut[nFlag++] = byte;
  }
  else{
   if (isspace(byte)){
    szOut[nFlag++] = '+';
   }
   else{
    szOut[nFlag++] = '%';
    szOut[nFlag++] = TOHEX(byte>>4);
    szOut[nFlag++] = TOHEX(byte%16);
   }
  }
 }
 szOut[nFlag] = '\0';
 strIn = szOut;

 delete[] szOut;
 return 0;
}

 

 

 

static void urldecode(char *p){
  int i=0;
  while(*(p+i))
  {
     if ((*p=*(p+i)) == '%')
     {
      *p=*(p+i+1) >= 'A' ? ((*(p+i+1) & 0XDF) - 'A') + 10 : (*(p+i+1) - '0');
      *p=(*p) * 16;
      *p+=*(p+i+2) >= 'A' ? ((*(p+i+2) & 0XDF) - 'A') + 10 : (*(p+i+2) - '0');
      i+=2;
     }
     else if (*(p+i)=='+')
     {
      *p=' ';
     }
     p++;
  }
  *p='\0';
 }