Click here to Skip to main content
13,350,289 members (45,416 online)
Click here to Skip to main content
Add your own
alternative version


5 bookmarked
Posted 21 Mar 2013

Introduction to Morse Code

, 15 Apr 2013
Rate this:
Please Sign up or sign in to vote.
Morse code encryption.


Morse code is a method of transmitting string information into a series of dots[.] and dashes[-] encrypting a message between two entities and so making communication possible between two parties. And we are going to have the fun task of doing just that.

I will be using a simple console application to represent the use of Morse code.

Using Morse

At first we will need to define a dictionary to be able to communicate. Find the Morse code value of the letter we want to type and instantiate a dictionary Element and the reason for doing so is that we will not have to use all of the redundant if statements or case statements thus increasing our calculation speeds.

namespace Morse_Code
    public class TheLib
        private Dictionary<String, String> m_TheLibrary = 
                      new Dictionary<string, string>();

        public Dictionary<String, String> TheLibrary
            get { return m_TheLibrary; }
            set { m_TheLibrary = value; }

This will keep track of all our data. Well now we have to add some data into our little library. Let's create a load method to do the adding of all our Morse values for our characters.

protected void LoadMorse()
    #region Alphabet A-Z
    TheLibrary.Add("A", ".-");
    TheLibrary.Add("B", "-...");
    TheLibrary.Add("C", "-.-.");
    TheLibrary.Add("D", "-..");

This will enable us to add some values into our library and using the library will be just as easy to do, just by calling on the library and sending our characters. Let's create a method that will return the Morse encrypted string value.

public String Sentance_To_Morse(String Sentence)
    //A single Space will identify inter character spaces in our words
    //A Triple Space will identify inter word spaces in our sentence
    String returnString = "";
    //We will start by deconstructing our sentence into a String List 
    //to hold our words in the sentence
    List<string> Words = Sentence.Split(' ').ToList<string>();//Convert the array to a list 
    //then we will loop through our words to start 
    //creating the Morse value for each letter in the list
    foreach (String Word in Words)
        for (int letter = 0; letter < Word.Length; letter++)
            //to upper is used to check if the value is in our library
            if (TheLibrary.ContainsKey(Word[letter].ToString().ToUpper()))
                returnString += TheLibrary[Word[letter].ToString().ToUpper()];//Gets the morse value for our letter
            }//Makes Sure That the character is in our library
                Console.WriteLine("The Character {0} is not recognized in the Morse Library", letter.ToString().ToUpper());
            }//tell the user there was a mistake
            returnString += " ";//add inter character space
        returnString = returnString.Trim(' ');  //remove the single space from the back to add
                                                //inter word space other wise we will have four spaces
        returnString += "   ";
    return returnString.Trim(' ');//to remove all unnecessary spaces

If we call on this method and send through the sentence "SOS SOS".

We will get the value of "... --- ... ... --- ..."

What if we got a series of dots and dashes and wanted to convert it back to a sentence? Let's create a method to do the conversion.

public String Morse_To_Sentance(String Morse)
    String returnString = "";
    //we will split the Code received into word segments remember the triple space
    //well now we will just replace that with a comma and split the Code on the comma
    Morse = Morse.Replace("   ", ",");
    string[] MorceWords = Morse.Split(',');
    foreach (String word in MorceWords)
        if (word != "")
            //remember the inter character spaces we assigned
            //now we will split the word into its charaters
            String[] MorseCodeLetters = word.Split(' ');
            foreach (string MorseCodeLetter in MorseCodeLetters)
                if (TheLibrary.ContainsValue(MorseCodeLetter))
                    //there is no get key by value in a dictionary thus we need to get the key manualy
                    foreach (KeyValuePair<String, String> MorseItem in TheLibrary)
                        if (MorseItem.Value == MorseCodeLetter)
                            returnString += MorseItem.Key;
        returnString += " ";//add inter word space
    return returnString.Trim(' ');//to remove all unnecessary spaces

And that will be all we need for our little converter. Hope this was a great example of a Morse code converter.

Now let's use the class we created:

static void Main(string[] args)
    TheLib m_lib = new TheLib();
    Console.Write("Type the Sentence you would like to encrypt to Morse ::");
    string MorseSentance = m_lib.Sentance_To_Morse(Console.ReadLine());
    Console.WriteLine("Your sentence has been encrypted to {0}", MorseSentance);

Points of Interest

Morse code was originally represented by sounds, beeps, and the methods bellow will play the Morse code to simulate a communication. Just add them to the library TheLib class and call on the method.

I used it three times as a long method. Well all it says basically is that a dash is three times as long as a dit and an inter character is as long as a dit.

protected void CreateDAH(int time)
    Console.Beep(1100, time);

protected void CreateDIT(int time)
    Console.Beep(1100, time);

public void playMessage(String message)
    message.ToList<char>().ForEach((c) =>
        if (c == '.') CreateDIT(200);
        else if (c == '-') CreateDAH(600);
        else Thread.Sleep(200);


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer Sybrin Systems
South Africa South Africa
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionTiming Issues Pin
George Swan22-Mar-13 0:51
memberGeorge Swan22-Mar-13 0:51 
AnswerRe: Timing Issues Pin
Kimahari22-Mar-13 9:49
memberKimahari22-Mar-13 9:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180111.1 | Last Updated 15 Apr 2013
Article Copyright 2013 by Kimahari
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid