Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Morse Code encoder/decoder (http://www.go4expert.com/articles/morse-code-encoder-decoder-t3090/)

pradeep 21Feb2007 11:15

Morse Code encoder/decoder
 
Morse code is a method for transmitting information, using standardized sequences of short and long elements, for the letters, numerals, punctuation and special characters of a message. The short and long elements can be formed by sounds, marks or pulses, and are commonly known as "dots" and "dashes" or "dits" and "dahs". There are short spaces between the dits and dahs within a character, longer ones between characters, and still longer ones between words.

Read more here

PHP Code:

$lettertomorse=array(
     
"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" => "--..",
     
"1" => ".----",
     
"2" => "..---",
     
"3" => "...--",
     
"4" => "....-",
     
"5" => ".....",
     
"6" => "-....",
     
"7" => "--...",
     
"8" => "---..",
     
"9" => "----.",
     
"0" => "-----",
     
" " => "   ",
     
"." => ".-.-.-",
     
"," => "--..--",
     
"EOM" => ".-.-."
     
);
 
 
$morsetoletter=array();
 
reset($lettertomorse);
 foreach(
$lettertomorse as $letter => $code
 {
     
$morsetoletter[$code]=$letter;
 }
 
 function 
morse_encode($txt
 {
     global 
$lettertomorse;
 
     
$line="";
     for (
$i=0;$i<strlen($txt);$i++) 
     {
         
$letter=substr($txt,$i,1);
 
         
// ignore unknown characters
         
if (empty($lettertomorse[$letter])) 
             continue;
 
         
$line.=$lettertomorse[$letter]." ";
     }
     return 
$line;
 }
 
 function 
morse_decode($string
 {
     global 
$morsetoletter;
 
     
$line="";
     
$letters=array();
     
$letters=explode(" ",$string);
     foreach (
$letters as $letter
     {
         
// ignore unknown characters
         
if (empty($letter)) 
             
$line.=" ";
         if (empty(
$morsetoletter[$letter])) 
             continue;
 
         
$line.=$morsetoletter[$letter];
     }
     return 
$line;
 } 

Example usage:
PHP Code:

print morse_encode("I Am Fine"); 



All times are GMT +5.5. The time now is 18:11.