Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Very simple C method to perform URL encoding on a char buffer. Includes a quick and dity list of characters to exclude. Some compilers will prefer sprintf_s or otherwise.
// ae - takes URL, puts percents in it.
void encodeUrl(char *out, int outSize, char *in, int inSize)
{
// Terminate our buffer
out[0] = '\0';
// Loop the input
for (int i = 0; i < inSize; i++)
{
// Get a char out of it
unsigned char c = in[i];
// Characters to exclude from this conversion
// These are for the requirements of this project,
// there is an RFC somewhere with what's meant to be here.
if ((c >= 46 && c <= 57) || // . / 0-9
(c >= 65 && c <= 90) || // A-Z
(c >= 97 && c <= 122) || // a-z
(c == 92) || // .
(c == 58)) // :
{
// Just add the char as-is
sprintf(out, outSize, "%s%c", out, c);
}
else
{
// Prepend a percent symbol, hex it
sprintf(out, outSize, "%s%c%02X", out, '%', c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.