Created
August 8, 2023 04:59
-
-
Save grantnorwood/854ea6548d7da6310a13537b7a0d4a44 to your computer and use it in GitHub Desktop.
Encode & decode strings for URLs in C++
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
/** | |
* Decode a URL-encoded string. | |
*/ | |
String urlDecode(String str) | |
{ | |
String encodedString = ""; | |
char c; | |
char code0; | |
char code1; | |
for (int i = 0; i < str.length(); i++) | |
{ | |
c = str.charAt(i); | |
if (c == '+') | |
{ | |
encodedString += ' '; | |
} | |
else if (c == '%') | |
{ | |
i++; | |
code0 = str.charAt(i); | |
i++; | |
code1 = str.charAt(i); | |
c = (h2int(code0) << 4) | h2int(code1); | |
encodedString += c; | |
} | |
else | |
{ | |
encodedString += c; | |
} | |
yield(); | |
} | |
return encodedString; | |
} | |
/** | |
* Encode a string for URLs. | |
*/ | |
String urlEncode(String str) | |
{ | |
String encodedString = ""; | |
char c; | |
char code0; | |
char code1; | |
char code2; | |
for (int i = 0; i < str.length(); i++) | |
{ | |
c = str.charAt(i); | |
if (c == ' ') | |
{ | |
encodedString += '+'; | |
} | |
else if (isalnum(c)) | |
{ | |
encodedString += c; | |
} | |
else | |
{ | |
code1 = (c & 0xf) + '0'; | |
if ((c & 0xf) > 9) | |
{ | |
code1 = (c & 0xf) - 10 + 'A'; | |
} | |
c = (c >> 4) & 0xf; | |
code0 = c + '0'; | |
if (c > 9) | |
{ | |
code0 = c - 10 + 'A'; | |
} | |
code2 = '\0'; | |
encodedString += '%'; | |
encodedString += code0; | |
encodedString += code1; | |
// encodedString+=code2; | |
} | |
yield(); | |
} | |
return encodedString; | |
} | |
/** | |
* Convert a character from hex to int. | |
*/ | |
unsigned char h2int(char c) | |
{ | |
if (c >= '0' && c <= '9') | |
{ | |
return ((unsigned char)c - '0'); | |
} | |
if (c >= 'a' && c <= 'f') | |
{ | |
return ((unsigned char)c - 'a' + 10); | |
} | |
if (c >= 'A' && c <= 'F') | |
{ | |
return ((unsigned char)c - 'A' + 10); | |
} | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment