Morse Code

Dave Sinkula 0 Tallied Votes 374 Views Share

This code uses a structure to map a letter to an equivalent representation of Morse code. It simply loops through either a string to encode or decode looking for text to substitute with a replacement string or character. Output is presented to the stdout.

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

static const struct
{
   const char letter, *morse;
} Code[] =
{
   { 'A', ".- "   },{ 'B', "-... " },{ 'C', "-.-. " },{ 'D', "-.. "  },
   { 'E', ". "    },{ 'F', "..-. " },{ 'G', "--. "  },{ 'H', ".... " },
   { 'I', ".. "   },{ 'J', ".--- " },{ 'K', ".-.- " },{ 'L', ".-.. " },
   { 'M', "-- "   },{ 'N', "-. "   },{ 'O', "--- "  },{ 'P', ".--. " },
   { 'Q', "--.- " },{ 'R', ".-. "  },{ 'S', "... "  },{ 'T', "- "    },
   { 'U', "..- "  },{ 'V', "...- " },{ 'W', ".-- "  },{ 'X', "-..- " },
   { 'Y', "-.-- " },{ 'Z', "--.. " },{ ' ', "  "    },
};

void encode(const char *s)
{
   size_t i, j;
   for ( i = 0; s[i]; ++i )
   {
      for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
      {
         if ( toupper(s[i]) == Code[j].letter )
         {
            printf("%s", Code[j].morse);
            break;
         }
      }
   }
   putchar('\n');
}

void decode(const char *morse)
{
   size_t i, j;
   for ( i = 0; morse[i]; )
   {
      for ( j = 0; j < sizeof Code / sizeof *Code; ++j )
      {
         size_t size = strlen(Code[j].morse);
         if ( memcmp(Code[j].morse, &morse[i], size) == 0 )
         {
            putchar(Code[j].letter);
            i += size;
            break;
         }
      }
   }
   putchar('\n');
}

int main(void) 
{
   const char text[] = "Hello world";
   const char test[] = ".... . .-.. .-.. ---   .-- --- .-. .-.. -.. ";
   encode(text);
   decode(test);
   return 0;
}

/* my output
.... . .-.. .-.. ---   .-- --- .-. .-.. -.. 
HELLO WORLD
*/