Percent-encode and decode URL query component strings in C
C
#include <ctype.h>
#include <string.h>
static int hexv(char c) { return isdigit((unsigned char)c) ? c - '0' : tolower((unsigned char)c) - 'a' + 10; }
void query_encode(const char *s, char *o, size_t n) {
for (; *s && n > 3; s++, n--) {
unsigned char c = (unsigned char)*s;
if (isalnum(c) || strchr("-_.~", c)) *o++ = (char)c;
else { *o++ = '%'; *o++ = "0123456789ABCDEF"[c >> 4]; *o++ = "0123456789ABCDEF"[c & 15]; n -= 2; }
}
*o = '\0';
}
int query_decode(const char *s, char *o, size_t n) {
for (; *s && n > 1; s++, n--) {
if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
*o++ = (char)(hexv(s[1]) * 16 + hexv(s[2]));
s += 2;
} else *o++ = (*s == '+') ? ' ' : *s;
}
*o = '\0';
return 0;
}