ROT13 Encoder Source Code

By | July 10, 2015

The ROT13 encoder is a fun programming exercise that my students enjoyed recently. I have included my source code here in PHP and C.

PHP

<?php
  function rot13($char)
  {
    $ascii = ord($char);

    if (($ascii >= 65) && ($ascii <= 90))
    {
      $val = ($ascii - 51) % 26;
      if ($val == 0)
      {
        $val = 26;
      }
      $val += 64;
    }
    else if (($ascii >= 97) && ($ascii <= 122)) 
    {
      $val = ($ascii - 83) % 26;
      if ($val == 0)
      {
        $val = 26;
      }
      $val += 96;
    }
    else
    {
      $val = $ascii;
    }
    return (chr($val));
  }

  function main()
  {
    $input = $_GET['text'];
    for ($i = 0; $i < strlen($input); $i++)
    {
      echo rot13($input[$i]);
    }
  }

  main();
?>

C

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int rot13(int x)
{
  int val;

  if (isupper(x))
  {
    val = (x - 51) % 26;
    if (val == 0)
    {
      val = 26;
    }
    val += 64;
  }
  else if (islower(x))
  {
    val = (x - 83) % 26;
    if (val == 0)
    {
      val = 26;
    }
    val += 96;
  }
  else
  {
    val = x;
  }
  return (val);
}

int main (int argc, char *argv[])
{
  if (argc > 0)
  {
    for (int i = 0; i < strlen(argv[1]); i++)
    {
      printf("%c", rot13(argv[1][i]));
    }
    printf("\n");
  }
  return (0);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.