In my earlier article where I showed how you can access YQL in Arduino, I mentioned that I wrote a quick and dirty function to do URLEncoding (percent encoding) in Arduino. While writing that function, I found a nice little trick about URL Encoding and thought of writing about it here.
At first, I just did a web search to see how you can do URL Encoding in C. I stumbled upon a question in stackoverflow and found that you have to use the curl_easy_escape function in libcurl. Since Arduino doesn’t have a port for libcurl (yet 😉 ) I had to write my own.
I did a web search again and came across an implementation of URLEncode in C by Umberto Salsi.
It was really simple and used a nice trick. Look at lines 11 and 12. Initially I didn’t understood it and so started reading RFC 3986. On page 11, it talks about how the encoding is done.
A percent-encoded octet is encoded as a character triplet, consisting of the percent character “%” followed by the two hexadecimal digits representing that octet’s numeric value. For example, “%20” is the percent-encoding for the binary octet “00100000” (ABNF: %x20), which in US-ASCII corresponds to the space character (SP)
After reading it things became clear and I was able understand the bit magic which Umberto Salsi was doing.
I modified the code so that it accepts the string that needs to be converted, instead of reading it from console and below is my version.
I hope the bit manipulation logic is clear. If not, let me know (by leaving a comment below) and I will write a blog post explaining it. Till then happy hacking 😉