// morse.cpp #include "morse.h" #include #include // This array has one element per printable character // starting with ' '. If I was trying for space and speed efficiency, // I could represent the same information using just 40 characters, // one for each of the Morse codes. const char Morse::charm[95][7] = { "", "", "", "", "", "", "", "", "", "", "", "", "--..--", "", ".-.-.-", "", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "---...", "-.-.-.", "", "", "", "", "", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "", "", "", "", "", "", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "", "", "", "" }; // mc has one character per morse code encoding as a number. // In the encoding '.' is represented as '0', '-' as '1'. // The encoded sequence is preceded by a '1' and it is interpreted as // a binary number. const char Morse::mc[128] = "--ETIANMSURWDKGOHVF-" "L-PJBXCYZQ--54-3---2" "-------16-------7---" "8-90----------------" "-----.--------------" "------;--------,----" ":------"; const char * Morse::char2morse(char c) { return charm[int(c)-int(' ')]; } char Morse::morse2char(const char * s) { int sum = 1; for (const char * p = s; (*p == '.') || (*p == '-'); p++) sum = 2*sum + (((*p)=='.')?0:1); return mc[(sum<127)?sum:0]; }