urldecode.c 929 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. from http://www.geekhideout.com/urlcode.shtml
  3. public domain
  4. */
  5. #include <ctype.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. /* Converts a hex character to its integer value */
  9. char from_hex(char ch) {
  10. return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
  11. }
  12. /* Converts an integer value to its hex character*/
  13. char to_hex(char code) {
  14. static char hex[] = "0123456789abcdef";
  15. return hex[code & 15];
  16. }
  17. /* Returns a url-decoded version of str */
  18. /* IMPORTANT: be sure to free() the returned string after use */
  19. char *url_decode(char *str) {
  20. char *pstr = str, *buf = malloc(strlen(str) + 1), *pbuf = buf;
  21. while (*pstr) {
  22. if (*pstr == '%') {
  23. if (pstr[1] && pstr[2]) {
  24. *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
  25. pstr += 2;
  26. }
  27. } else if (*pstr == '+') {
  28. *pbuf++ = ' ';
  29. } else {
  30. *pbuf++ = *pstr;
  31. }
  32. pstr++;
  33. }
  34. *pbuf = '\0';
  35. return buf;
  36. }