-
-
Save jesobreira/4ba48d1699b7527a4a514bfa1d70f61a to your computer and use it in GitHub Desktop.
URL Encoding in C (urlencode / encodeURIComponent)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
char* urlencode(char* originalText) | |
{ | |
// allocate memory for the worst possible case (all characters need to be encoded) | |
char *encodedText = (char *)malloc(sizeof(char)*strlen(originalText)*3+1); | |
const char *hex = "0123456789abcdef"; | |
int pos = 0; | |
for (int i = 0; i < strlen(originalText); i++) { | |
if (('a' <= originalText[i] && originalText[i] <= 'z') | |
|| ('A' <= originalText[i] && originalText[i] <= 'Z') | |
|| ('0' <= originalText[i] && originalText[i] <= '9')) { | |
encodedText[pos++] = originalText[i]; | |
} else { | |
encodedText[pos++] = '%'; | |
encodedText[pos++] = hex[originalText[i] >> 4]; | |
encodedText[pos++] = hex[originalText[i] & 15]; | |
} | |
} | |
encodedText[pos] = '\0'; | |
return encodedText; | |
} | |
int main() | |
{ | |
printf("%s", urlencode("Hello / world =")); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks, short version:
static void urlencode(char * s, char * d)
{
const char *hex = "0123456789ABCDEF";
}