การบ้าน digital ครั้งที่ 1 ส่งวันที่ 19 พฤศจิกายน 2550

จัดทำโดย นางสาวณัฐฐา ดำรงสุนทรชัย
รหัสนิสิต 49053838
code งานการ convert gray code <==> binary code

 

using System;
class graybinary{
static void gray(string g){
char[] gi=new char[g.Length+1];// number of gray when change

gi[0]='0';
if(g[0]=='1'){
gi[1]='1';
}
else{
gi[1]='0';
}

for(int i=1;i<g.Length;i++){
if(g[i]==gi[i]){
gi[i+1]='0';
}
else{
gi[i+1]='1';
}
}
Console.Write("Convert to binary code:");
for(int j=1;j<gi.Length;j++){
Console.Write(gi[j]);
}
Console.ReadLine();
}

static void bina(string bi){
char[] bii=new char[bi.Length+1];
char[] gg=new char[bi.Length];
bii[0]='0';

for(int i=0;i<bi.Length;i++){
bii[i+1]=bi[i];
}

for(int j=0;j<bii.Length-1;j++){
if(bii[j]==bii[j+1]){
gg[j]='0';
}
else{
gg[j]='1';
}
}
Console.Write("Convert to gray code:");
for(int i=0;i<bii.Length-1;i++){
Console.Write(gg[i]);
}
Console.ReadLine();
}

static void Main(){
Console.WriteLine("Please input type of code : ");
Console.WriteLine("Enter g : Convert from gray code to binary code");
Console.WriteLine("Enter b : Convert from binary code to gray code");
Console.WriteLine("-------------------------------------------------");
Console.Write("Enter : ");
string insert=Console.ReadLine();
//Console.Write(insert[0]);
while(insert[0]!='g'||insert[0]!='b'){

if(insert[0]=='g'||insert[0]=='b'){ break;}
else{Console.WriteLine("Please try again!!");
Console.Write("Enter :");
insert=Console.ReadLine();
}
}

//change gray code to binary code
if(insert[0]=='g'){
Console.Write("input gray code:");
string g=Console.ReadLine();
int u=0;
if(g.Length>16){
while(g.Length>16){

if(g.Length<=16){ break;}
else{
Console.Write("Please input gray code again:");
g=Console.ReadLine();
if(g.Length<=16){u=9;break;}
}
}
}

if(u==9){
gray(g);
}

else{
gray(g);
}

}

//change from binarycode to gray code
else if(insert[0]=='b'){
Console.Write("input binary code:");
string bi=Console.ReadLine();
int y=0;
if(bi.Length>16){

while(bi.Length>16){

if(bi.Length<=16){ break;}
else{
Console.Write("Please input binary code again:");
bi=Console.ReadLine();
if(bi.Length<=16){y=9;break;}
}
}

}

if(y==9){
bina(bi);
}

else{

bina(bi);


}

}
}
}

กลับหน้าหลัก

Hosted by www.Geocities.ws

1