/* URL encoding C version * Lin Jensen * Feb 21, 1999 * A new string is produced, URL encoded. Rules are * Alphanumeric chars unchanged * Space --> '+' * Special chars (the rest) --> "%hh" where hh is hexadecimal ************************************************************************/ #include char bin2hex (char ch){ /* return ascii char for hex value of rightmost 4 bits of input */ ch = ch & 0x0f; /* mask off right nibble - & bitwise AND*/ ch += '0'; /* make ascii '0' - '9' */ if (ch > '9') ch += 7; /* account for 7 chars between '9' and 'A' */ return (ch); } int AlphaNumeric (char ch){ return ((ch >='a') && (ch <= 'z') || /* logical AND &&, OR || */ (ch >='A') && (ch <= 'Z') || (ch >='0') && (ch <= '9') ); } int URLencode (const char * plain, char * encode, int maxlen){ char ch; /* each char, use $t2 */ char * limit; /* point to last available location in encode */ char * start; /* save start of encode for length calculation */ limit = encode + maxlen - 4; /* need to store 3 chars and a zero */ ch = *plain ++; /* get first character */ while (ch != 0) { /* end of string, asciiz */ if (ch == ' ') * encode ++ = '+'; else if (AlphaNumeric (ch)) * encode ++ = ch; else { * encode ++ = '%'; * encode ++ = bin2hex (ch >> 4); /*shift right for left nibble*/ * encode ++ = bin2hex (ch); /* right nibble */ } ch = *plain ++; /* ready for next character */ if (encode > limit){ *encode = 0; /* still room to terminate string */ return (-1); /* get out with error indication */ } } * encode = 0; /* store zero byte to terminate string */ return (encode - start); /* done, return count of characters */ } /* URLencode*/ void main() { char * sample = "This is my string, $2.95!"; char result[50]; URLencode (sample, result, 50); printf ("%s\n%s\n", sample, result); }