Skip to content

Instantly share code, notes, and snippets.

@alanedwardes
Created March 14, 2014 00:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanedwardes/9539795 to your computer and use it in GitHub Desktop.
Save alanedwardes/9539795 to your computer and use it in GitHub Desktop.
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