New Page 1
Morse码翻译的小程序
A.第一版
这个小程序是最初的版本。
1。 程序基本说明:大家应该都听说过“莫尔斯密码”吧?这个练习程序就是把Morse码与字符相互转换。
2。 游戏程序思路:我们用的是ASCII码,Morse码无非是另一种编码系统,只要做个对照表就可以了,根本不用写程序的!只是为了好看才
	写一个打印Morse码的程序,Morse码的样子见下图,大家可以看到它实际上是一个不定长度的“二进制码”,我一开始想用每个Byte
	中的5个Bit来存放Morse码,后来做下去才发现不定长码必须要实际上要三个码才能表示,除非按照“哈夫曼”编码原则,我就偷懒用
	3个Bit来存放Morse码里的“.”和“-”以及“空”。Morse码最长5个,所以3x5=15,用两个Byte的int来存刚好多一个。
3。 主要函数介绍:
	A. 为了输出Morse码而设定的每个字符的一种自定义的掩码Mask,即用三个Bit表示出的1(001), 2(010)分别代表Morse码里的
	点(.)和划(-)。 如:A在Morse码里是“.-”,则我的掩码就是0000 0000 0000 1010,翻成十进制就是10,依靠这个掩码我就
	可以输出对应的Morse码了。	
	


4。 不足之处:
应该可以用“哈夫曼”编码来解决不定长编码,不过我还没有学懂,只看了个开头。



int Code[36] =

{10, 1097, 1105, 137, 1, 593, 145, 585, 9, 658, //j
1105, 649, 18, 17, 146, 657, 1162, 81, 73, 2, 74, 586, //v
82, 1098, 1106, 1161, //z
9362, //0
5266, //1
4754, 4690, 4682, 4681, 8777, 9289, 9353, 9361 //9
};

B. 这个函数非常简单就是将字符转成A数组的序列(Index).

short toMorse(char );

C. 这个函数才是利用A里的掩码与B里的序列号输出Morse码。就是用3(111)这个掩码来将A里的掩码每3个Bit进行与操作得到的结果,

如为1就是“.”,2就是“-”,其余放空。

void printMorse(int );







#include <fstream>
using namespace std;
int Code[36] = {10, 1097, 1105, 137, 1, 593, 145, 585, 9, 658, //j
1105, 649, 18, 17, 146, 657, 1162, 81, 73, 2, 74, 586, //v
82, 1098, 1106, 1161, //z
9362, //0
5266, //1
4754, 4690, 4682, 4681, 8777, 9289, 9353, 9361 //9
};
short toMorse(char );
char fromMorse(short );
void printMorse(int );
void translate(char *);
void demo();
int main()
{
demo();
return 0;
}
void demo()
{
void doDemo(short start, short end);
doDemo('a', 'z');
doDemo('0', '9');
}
void doDemo(short start, short end)
{
for (short ch = start; ch<=end; ch++)
{
cout<<(char)(ch)<<" is equal to Morse code: ";
printMorse(Code[toMorse((char)(ch))]);
cout<<((ch-start+1)%2 != 0?'\t':'\n');
}
cout<<endl;
}
void translate(char *str)
{
char *pch = str;
short index;
	
while (*pch!='\0')
{
if (*pch == 32)
{
cout<<" ";
}
else
{
index = toMorse(*pch);
if (index != -1)
{
printMorse(Code[index]);
}
}
pch++;
}
}
short toMorse(char ch)
{
	if (ch>='A'&&ch<='Z')
{
return ch - 'A';
}
else
{
if (ch>='a'&&ch<='z')
{
return ch - 'a';
}
else
{
if (ch>='0'&&ch<='9') // '0' < '9'????
{
return ch - '0' + 26;
}
else
{
return - 1;
}
}
}
}
char fromMorse(short code)
{
if (code >=0&&code<=25)
{
return (char)(code + 'A');
}
else
{
if (code>=26&&code<=35)
{
return (char)(code - 26 + '0');
}
else
{
return '\0';
}
}
}
void printMorse(int code)
{
int mask = 3, result = 0;
	for (int i = 4; i>=0; i--)
{
result = code>> i * 3;
result = mask & result;
switch (result)
{
case 1:
cout<<'.';
break;
case 2:
cout<<'-';
break;
default:
break;
}
}
cout<<" ";
}
Click to enlarge.

                                                                     back.gif (341 bytes)      up.gif (335 bytes)       next.gif (337 bytes)