Kjetil's Information Center: A Blog About My Projects

URL Decoder and Encoder

Here are some simple C-based filter programs to decode and encode URL-encoded hex characters.

The "decoder", detects and decodes any URL-encoded characters in the stream:

#include <stdio.h>

static int from_hex(char c)
{
  switch (c) {
  case '0':
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9':
    return c - 0x30;
  case 'A':
  case 'B':
  case 'C':
  case 'D':
  case 'E':
  case 'F':
    return c - 55;
  case 'a':
  case 'b':
  case 'c':
  case 'd':
  case 'e':
  case 'f':
    return c - 87;
  }
  return 0;
}

int main(void)
{
  int c, in_code, first_hex;

  in_code = 0;
  while ((c = fgetc(stdin)) != EOF) {
    if (in_code == 1) {
      first_hex = from_hex(c);
      in_code++;
    } else if (in_code == 2) {
      fputc(from_hex(c) + (first_hex * 16), stdout);
      in_code = 0;
    } else {
      if (c == '%') {
        in_code = 1;
      } else {
        fputc(c, stdout);
      }
    }
  }

  return 0;
}
          


The "encoder", simply encodes every character into the URL-encoded counter-part:

#include <stdio.h>

static char to_hex(int n)
{
  switch (n) {
  case 0:
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
  case 6:
  case 7:
  case 8:
  case 9:
    return n + 0x30;
  case 10:
  case 11:
  case 12:
  case 13:
  case 14:
  case 15:
    return n + 55;
  }
  return '?';
}

int main(void)
{
  int c;

  while ((c = fgetc(stdin)) != EOF) {
    fputc('%', stdout);
    fputc(to_hex(c / 16), stdout);
    fputc(to_hex(c % 16), stdout);
  }

  return 0;
}
          


Topic: Scripts and Code, by Kjetil @ 27/10-2012, Article Link