URL Encoding
URL-encodes string. This algorithm is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
char* DecimalToHexadecimal(int dec)
{
if (dec < 1) return "0";
int hex = dec;
char hexStr[8];
int i = 0;
char temp;
while (dec > 0)
{
hex = dec % 16;
if (hex < 10) {
temp = (char)(hex + 48);
}
else {
temp = (char)(hex + 55);
}
hexStr[i++] = temp;
dec /= 16;
}
for (int j = 0; j < i - 1; j++)
{
temp = hexStr[j];
hexStr[j] = hexStr[(i - j) - 1];
hexStr[(i - j) - 1] = temp;
}
hexStr[i] = '\0';
return hexStr;
}
char* URLEncoding(char* data, unsigned int count) {
char* result = malloc(1);
result[0] = '\0';
for (int i = 0; i < count; ++i)
{
char c = data[i];
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9'))
{
strncat(result, &c, 1);
}
else
{
strncat(result, "%", 1);
char s[3] = { '0', '0', '\0' };
char* hexStr = DecimalToHexadecimal(c);
if (strlen(hexStr) < 2) {
s[1] = hexStr[0];
}
else {
s[0] = hexStr[0];
s[1] = hexStr[1];
}
strcat(result, s);
}
}
return result;
}
Example
char* data = "jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^";
char* value = URLEncoding(data, strlen(data));
Output
jdfgsdhfsdfsd%206445dsfsd7fg%2F%2A%2F%2Bbfjsdgf%25%24%5E