Morse Code Translator
  1. Translator
  2. Programming

Morse code programming

Translate text to Morse with a character lookup table and decode complete tokens with the reverse lookup. These runnable examples share a simple format: spaces between letters and slash tokens between words.

To build a Morse code JavaScript translator, pair each supported character with its Morse string. Encode by looking up characters; decode by looking up complete Morse tokens. The examples below implement that same small format in JavaScript, C, C++ and Rust.

Choose a text format before you write the decoder

These programs support ASCII letters A–Z, lowercase a–z and digits 0–9. The character patterns come from the International Morse table (ITU). The source code generates its lookup data from this site's Morse code alphabet; you do not need to transcribe a chart. The examples deliberately leave punctuation out so you can inspect the entire translator without maintaining a second set of rules.

A laptop and a Morse practice key rest beside a looping cable.
Illustration: Connecting code and practice

Our file format uses one ASCII space between letter tokens and a slash token for each input space. A slash here is a word separator chosen for the program. It does not represent the Morse character for a literal slash. Each decoder reads a complete token before looking it up. That boundary matters: joining all the marks into one uninterrupted string discards the character boundaries your lookup requires.

The encoders convert ASCII lowercase letters to uppercase and replace unsupported input with a literal question mark. The decoders also return a question mark for an unknown token. This marker is an error placeholder, not encoded punctuation. These choices make unsupported input visible, but they do lose information. Keep the original text if you need to diagnose the position of an error later.

Morse code JavaScript: encode and decode

Save this as morse.js and run node morse.js. A JavaScript Map holds key-value pairs, and get() returns the matching value when a key is present (MDN). The forward map stores a character as its key. The reverse map stores its Morse token as the key. The fallback question mark handles either missing lookup.

const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const codes = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."];
const forward = new Map([...letters].map((c, i) => [c, codes[i]]));
const reverse = new Map(codes.map((c, i) => [c, letters[i]]));

function encode(text) {
  return [...text].map(c => {
    if (c === " ") return "/";
    return forward.get(c.replace(/[a-z]/g, x => x.toUpperCase())) ?? "?";
  }).join(" ");
}
function decode(morse) {
  return morse.split(" ").filter(Boolean)
    .map(c => c === "/" ? " " : reverse.get(c) ?? "?").join("");
}
const message = encode("Hello 2026");
console.log(message);
console.log(decode(message));
console.log(encode("@"), decode("?"));

The two maps are built once. The functions then work on their arguments without changing those maps. Replace the greeting in the final lines with your own ASCII phrase. Compare the result with the online Morse code translator before changing how tokens are separated.

Morse code in C: print without an output buffer

Save this as morse.c. Compile with cc -std=c11 -Wall -Wextra -Werror morse.c -o morse-c, then run ./morse-c. These functions print their results directly. You supply a null-terminated input string; you do not supply a fixed-size destination buffer. That keeps this small example free of output-capacity calculations.

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

static const char letters[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static const char *codes[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."};

void encode(const char *text) {
    for (size_t i = 0; text[i]; ++i) {
        if (i) putchar(' ');
        char c = text[i];
        if (c >= 'a' && c <= 'z') c -= 'a' - 'A';
        const char *p = strchr(letters, c);
        fputs(c == ' ' ? "/" : p ? codes[p - letters] : "?", stdout);
    }
    putchar('\n');
}
void decode(const char *morse) {
    while (*morse) {
        morse += strspn(morse, " ");
        size_t n = strcspn(morse, " ");
        if (!n) break;
        char c = '?';
        if (n == 1 && *morse == '/') c = ' ';
        else for (size_t i = 0; i < sizeof letters - 1; ++i)
            if (strlen(codes[i]) == n && !strncmp(morse, codes[i], n)) {
                c = letters[i];
                break;
            }
        putchar(c);
        morse += n;
    }
    putchar('\n');
}
int main(void) {
    encode("Hello 2026");
    decode(".... . .-.. .-.. --- / ..--- ----- ..--- -....");
    encode("@");
    decode("?");
}

The decoder measures a token, compares both its length and contents, then advances to the next token. Testing the length prevents a short prefix from matching a longer code. The encoder searches the parallel character string to find the corresponding table index. Keep the character string and code array in the same order whenever you extend the table.

Morse code C++: return strings

Save this as morse.cpp. Compile with c++ -std=c++17 -Wall -Wextra -Werror morse.cpp -o morse-cpp, then run ./morse-cpp. This version returns strings, so you can pass an encoded result straight into the decoder. The encoder checks the result of its character search before indexing the table; the string search rules are documented in the C++ working draft (C++ working draft).

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

const std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const std::vector<std::string> codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."};

std::string encode(const std::string& text) {
    std::string out;
    for (char c : text) {
        if (!out.empty()) out += ' ';
        if (c >= 'a' && c <= 'z') c -= 'a' - 'A';
        auto i = letters.find(c);
        out += c == ' ' ? "/" : i == std::string::npos ? "?" : codes[i];
    }
    return out;
}
std::string decode(const std::string& morse) {
    std::istringstream in(morse);
    std::string token, out;
    while (in >> token) {
        char c = '?';
        if (token == "/") c = ' ';
        else for (std::size_t i = 0; i < codes.size(); ++i)
            if (codes[i] == token) { c = letters[i]; break; }
        out += c;
    }
    return out;
}
int main() {
    auto message = encode("Hello 2026");
    std::cout << message << '\n' << decode(message) << '\n';
    std::cout << encode("@") << ' ' << decode("?") << '\n';
}

The decoder reads tokens from a string stream. The examples produce ordinary spaces between tokens; this decoder also accepts whitespace recognized by the stream. To turn this into a command-line utility, read a line of text and choose encode or decode explicitly. Do not guess the direction solely from whether a line contains a slash.

Morse code Rust: two lookup directions

Save this as morse.rs. Compile with rustc --edition=2021 morse.rs -o morse-rust, then run ./morse-rust. Rust's HashMap::get returns an optional reference to a matching value (Rust documentation). This example copies the small lookup result and supplies the visible error marker when the lookup fails.

use std::collections::HashMap;

fn encode(text: &str) -> String {
    let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let codes = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."];
    let map: HashMap<_, _> = letters.chars().zip(codes).collect();
    text.chars().map(|c| {
        if c == ' ' { "/" }
        else { map.get(&c.to_ascii_uppercase()).copied().unwrap_or("?") }
    }).collect::<Vec<_>>().join(" ")
}
fn decode(morse: &str) -> String {
    let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let codes = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."];
    let map: HashMap<_, _> = codes.into_iter().zip(letters.chars()).collect();
    morse.split_whitespace().map(|token| {
        if token == "/" { ' ' }
        else { map.get(token).copied().unwrap_or('?') }
    }).collect()
}
fn main() {
    let message = encode("Hello 2026");
    println!("{}\n{}", message, decode(&message));
    println!("{} {}", encode("@"), decode("?"));
}

Both functions construct their own maps to keep the example self-contained. For a service that translates many messages, pass prepared maps into the functions instead. Preserve the same character normalization and separator contract when you refactor, then compare the old and new results on the same inputs.

Output from the executed programs

JavaScript, C++ and Rust printed this identical output. The last line exercises an unsupported character and an unknown token:

.... . .-.. .-.. --- / ..--- ----- ..--- -....
HELLO 2026
? ?

The C program printed the same encoded greeting and decoded text, followed by each error marker on its own line:

.... . .-.. .-.. --- / ..--- ----- ..--- -....
HELLO 2026
?
?

What about Morse code in Java, C# and Go?

To implement this format in Java, C# or Go, keep the same character table, uppercase conversion, slash tokens and unknown-character marker. Test your implementation against the output above, then check the boundary cases below. For another runnable approach, use the Python encoder and decoder.

Check boundaries before adding sound

Try an empty string, every supported letter and digit, lowercase input, repeated spaces, and an unsupported character. For supported ASCII text, decoding an encoded value should recover the original with letters uppercased. These examples preserve input spaces as slash tokens; they do not preserve the spacing between tokens in manually supplied Morse. JavaScript splits on ASCII spaces, while the Rust and C++ versions accept broader whitespace between tokens. Use the documented ASCII-space format when exchanging output among all four programs.

A text decoder does not measure sound or light. Add a separate timing layer if you want playback. Morse timing and gaps covers that next step. For practice with the result, start with the phrase below and use the listening lessons to recognize it by ear.

This player is separate from the text-only programs above.

For another programming task, try unique Morse word encodings.

To explore character-by-character decoding, see the Morse decoding tree.

Sources

  1. Recommendation ITU-R M.1677-1, International Morse code. ITU, October 2009.
  2. Map: JavaScript reference. MDN, checked 11 November 2026.
  3. C++ working draft: string.find. C++ working draft, checked 11 November 2026.
  4. std::collections::HashMap. Rust documentation, checked 11 November 2026.