vcmorini:
Feel free to use or to provide a better solution:
[code]
String hex2ascii(String string)
{
string.replace("%21", "!");
string.replace("%23", "#");
string.replace("%24", "$");
string.replace("%25", "%");
string.replace("%26", "&");
string.replace("%27", "'");
string.replace("%28", "(");
string.replace("%29", ")");
string.replace("%2A", "*");
string.replace("%2B", "+");
string.replace("%2C", ",");
string.replace("%2F", "/");
string.replace("%3A", ":");
string.replace("%3B", ";");
string.replace("%3D", "=");
string.replace("%3F", "?");
string.replace("%40", "@");
string.replace("%5B", "[");
string.replace("%5D", "]");
string.replace("%20", " ");
string.replace("%22", """");
string.replace("%2D", "-");
string.replace("%2E", ".");
string.replace("%3C", "<");
string.replace("%3E", ">");
string.replace("%5C", "\");
string.replace("%5E", "^");
string.replace("%5F", "_");
string.replace("%60", "`");
string.replace("%7B", "{");
string.replace("%7C", "|");
string.replace("%7D", "}");
string.replace("%7E", "~");
string.replace("%C2%A3", "£");
return string;
}
[/code]
Regards
I found a few issues with your function:
- This will give the wrong output for something like "%2526" (it should be "%26", but it incorrectly gives "&").
- "%22" is replaced with nothing.
- None of the characters 01 through 1F are handled.
- It cannot handle lower-case digits a-f.
It creates and destroys a lot of String objects (very wasteful).
- "%C2%A3" is UTF-8, not ASCII.
I would write a function that follows PaulS's and nickgammon's advice from 4 years ago:
nickgammon:
Like PaulS says, if you hit a %, take the next two (hex) characters, then convert that group (of 3) into one ASCII byte. (eg. %20 is space, etc.).
Edit: I was wrong on this point:
- It creates and destroys a lot of String objects (very wasteful).
There's only one String being modified in-place, not a lot of String objects created and destroyed.