Advertisement
obernardovieira

urlencode & urldecode

Apr 2nd, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. //not by me
  2.  
  3. unsigned char to_hex( unsigned char x )
  4. {
  5.     return x + (x > 9 ? ('A'-10) : '0');
  6. }
  7.  
  8. const std::string urlencode( const std::string& s )
  9. {
  10.     std::ostringstream os;
  11.  
  12.     for ( std::string::const_iterator ci = s.begin(); ci != s.end(); ++ci )
  13.     {
  14.         if ( (*ci >= 'a' && *ci <= 'z') ||
  15.                 (*ci >= 'A' && *ci <= 'Z') ||
  16.                 (*ci >= '0' && *ci <= '9') )
  17.         { // allowed
  18.             os << *ci;
  19.         }
  20.         else if ( *ci == ' ')
  21.         {
  22.             os << '+';
  23.         }
  24.         else
  25.         {
  26.             os << '%' << to_hex(*ci >> 4) << to_hex(*ci % 16);
  27.         }
  28.     }
  29.  
  30.     return os.str();
  31. }
  32.  
  33. unsigned char from_hex (
  34.     unsigned char ch
  35. )
  36. {
  37.     if (ch <= '9' && ch >= '0')
  38.         ch -= '0';
  39.     else if (ch <= 'f' && ch >= 'a')
  40.         ch -= 'a' - 10;
  41.     else if (ch <= 'F' && ch >= 'A')
  42.         ch -= 'A' - 10;
  43.     else
  44.         ch = 0;
  45.     return ch;
  46. }
  47.  
  48. const std::string urldecode (
  49.     const std::string& str
  50. )
  51. {
  52.     using namespace std;
  53.     string result;
  54.     string::size_type i;
  55.     for (i = 0; i < str.size(); ++i)
  56.     {
  57.         if (str[i] == '+')
  58.         {
  59.             result += ' ';
  60.         }
  61.         else if (str[i] == '%' && str.size() > i+2)
  62.         {
  63.             const unsigned char ch1 = from_hex(str[i+1]);
  64.             const unsigned char ch2 = from_hex(str[i+2]);
  65.             const unsigned char ch = (ch1 << 4) | ch2;
  66.             result += ch;
  67.             i += 2;
  68.         }
  69.         else
  70.         {
  71.             result += str[i];
  72.         }
  73.     }
  74.     return result;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement