Created
June 27, 2012 11:18
-
-
Save piranna/3003439 to your computer and use it in GitHub Desktop.
Functions to encode and decode strings to be valid URL ones
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* urlencode.c | |
* | |
* Based on code from http://www.zedwood.com/article/111/cpp-urlencode-function | |
* | |
* Created on: 21/06/2012 | |
* Author: piranna | |
*/ | |
#include "urlencode.hpp" | |
#include <stdlib.h> | |
//based on javascript encodeURIComponent() | |
string urlencode(const string &c) | |
{ | |
string escaped=""; | |
for(unsigned int i=0; i<c.length(); i++) | |
if((48 <= c[i] && c[i] <= 57) //0-9 | |
|| (65 <= c[i] && c[i] <= 90) //abc...xyz | |
|| (97 <= c[i] && c[i] <= 122) //ABC...XYZ | |
|| c[i]=='~' || c[i]=='!' || c[i]=='*' | |
|| c[i]=='(' || c[i]==')' || c[i]=='\'') | |
{ | |
escaped.append(&c[i], 1); | |
} | |
else | |
{ | |
escaped.append("%"); | |
escaped.append(char2hex(c[i])); // converts char 255 to string "ff" | |
} | |
return escaped; | |
} | |
string urldecode(const string &c) | |
{ | |
string result=""; | |
for(unsigned int i=0; i<c.length(); i++) | |
{ | |
if(c[i] == '%') | |
{ | |
// converts string "ff" to char 255 | |
char ret = hex2char(c.substr(i+1, 2)); | |
result.append(&ret, 1); | |
i += 2; | |
} | |
else | |
result.append(&c[i], 1); | |
} | |
return result; | |
} | |
string char2hex( char dec ) | |
{ | |
char dig1 = (dec&0xF0)>>4; | |
char dig2 = (dec&0x0F); | |
if(dig1 >= 0) | |
{ | |
if(dig1 <= 9) //0,48inascii | |
dig1 += 48; | |
else if(dig1 <= 15) //a,97inascii | |
dig1 += 97-10; | |
} | |
if(dig2 >= 0) | |
{ | |
if(dig2 <= 9) | |
dig2 += 48; | |
else if(dig2 <= 15) | |
dig2 += 97-10; | |
} | |
string r; | |
r.append(&dig1, 1); | |
r.append(&dig2, 1); | |
return r; | |
} | |
char hex2char(string hex) | |
{ | |
char result = strtoul(hex.c_str(), NULL, 16); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment