Morse Code Filter

I’m certain that the nerds would love debating whether the telegraph’s Morse code system was the first binary communications network. Let them do so. Still, Morse code remains a simple communications system, translating letters and numbers into dots and dashes — which you could argue are similar to ones and zeros.

Surprisingly, Morse code (obligatory Wikipedia link) has no official value for space or any punctuation characters. Its codes represent alphabetic letters A to Z, digits 0 through 9. A pause, or gap, in transmission separates letters, words, and so on, which is where the nerds could argue makes the system ternary and not binary.

Regardless, your task for this month’s Exercise is to concoct a filter that translates standard input into Morse code characters, period (.) for dot and hyphen (-) for dash. Opinions differ on how to represent the translation when output as text, so my advice for your code is to output words on a line by themselves. Separate the character codes with spaces (see below). Don’t output anything for punctuation or other undefined characters.

Here’s a sample run of my code:

Goodbye, cruel world!
--. --- --- -.. -... -.-- .
-.-. .-. ..- . .-..
.-- --- .-. .-.. -..

See how each word appears on a line by itself, with the codes (dots and dashes) separated by spaces?

To help get you started, here is a code skeleton you can build upon:

#include <stdio.h>

void toMorse(char c)
{
    char *morse_alpha[] = {
        ".-", "-...", "-.-.", "-..", ".", "..-.",
        "--.", "....", "..", ".---", "-.-", ".-..",
        "--", "-.", "---", ".--.", "--.-", ".-.",
        "...", "-", "..-", "...-", ".--", "-..-",
        "-.--", "--.."
    };
    char *morse_digit[] = {
        "-----", ".----", "..---", "...--", "....-",
        ".....", "-....", "--...", "---..", "----."
    };

    /* your solution goes here */
}

int main()
{
    int ch;

    while(1)
    {
        ch = getc(stdin);
        if( ch==EOF )
            break;
        toMorse(ch);
    }

    return(0);
}

Your task is to code the full toMorse() function.

Please try this Exercise on your own before you peek at my solution.

One thought on “Morse Code Filter

  1. “I’m certain that the nerds would love debating whether the telegraph’s Morse code system was the first binary communications network.” Quote from Turing’s Cathedral by George Dyson:

    That two symbols were sufficient for encoding all communication had been established by Francis Bacon in 1623. “The transposition of two Letters by five placeings will be sufficient for 32 Differences [and] by this Art a way is opened, wehereby a man may express and signifie the intentions of his minde, at any distance of place, by objects . . . capable of a twofold difference onely” he wrote, before giving examples of how such binary coding could be conveyed at the speed of paper, the speed of sound, or the speed of light.

Leave a Reply