'programming/C_C++'에 해당되는 글 279건

  1. 2014.02.11 URL Encoding / URL Decoding

반응형

/*** URL Encoding ***/
int urlEncode(unsigned char *source, unsigned char *dest)
{
  unsigned char hex[4];
  unsigned char *sbuf;
  int size = 0;

  sbuf = dest;

  while(*source) {
    /*** RFC 3986 section 2.3 Unreserved Characters ***/
    if ((*source > 47 && *source < 58) ||
        (*source > 64 && *source < 91) ||
        (*source > 96 && *source < 123) ||
        *source == '-' || *source == '_' || *source == '.' || *source == '~') {
      *sbuf = *source;
    }
    else {
      sprintf((char *)hex, "%%%02X", *source);
      strncat((char *)sbuf, (char *)hex, 3);
      *sbuf++;
      *sbuf++;
      size += 2;
    }
    *source++;
    *sbuf++;
    size++;
  }

  sbuf[size] = '\0';

  return size;
}

/*** URL Decoding ***/
int urlDecode(unsigned char *source, unsigned char *dest)
{
  int num=0, i, index=0;
  int retval=0;

  while(*source) {
    if (*source == '%') {
      num = 0;
      retval = 0;
      for (i = 0; i < 2; i++) {
        *source++;
        if (*(source) < ':') {
          num = *(source) - 48;
        }
        else if (*(source) > '@' && *(source) < '[') {
          num = (*(source) - 'A')+10;
        }
        else {
          num = (*(source) - 'a')+10;
        }

        if ((16*(1-i)))
          num = (num*16);
        retval += num;
      }
      dest[index] = retval;
      index++;
    }
    else {
      dest[index] = *source;
      index++;
    }
    *source++;
  }

  dest[index] = '\0';

  return index;
}

 

반응형
Posted by 공간사랑
,