//CIS 610-251: Data Structures and Algorithms. //Assignment #1 Sept 9,1999 //Object: Ternary to Binary Vice-versa Conversion //Platform: Visual C++ 5.0 #include #include class String { private: char * value; public: String() ; String(char*); int Length(); int BaseNTo10(int); String Base10ToN(int,int); char * getValue(); }; String::String() { value=new char[33]; int i=0; for(;i<32;i++) value[i]=48; value[32]=NULL; } String::String(char* Str) { value = new char[33]; value[32]=NULL; String temp;temp.value=Str; int LengthofStr=temp.Length(); if (LengthofStr > 32) { temp.value[32]=NULL;value=temp.value; } else if (LengthofStr < 32) { int i=LengthofStr; for(;i>-1;i--) value[32-i]=temp.value[LengthofStr-i]; for(i=0;i<32-LengthofStr;i++) value[i]='0'; } else { value=temp.value; } } int String::Length(void) { int len=0; for(;*(value+len);len++); return len; } //Given Base N convert to decimal int String::BaseNTo10(int baseN) { int total=0,i=31; for(;i>-1;i--) total+=(this->value[i]-48)* pow(baseN,31-i); return total; } //Given Base 10 convert to base N. String String::Base10ToN(int dec,int base) { String result; int i=31; while (i>-1 && dec >=base) { result.value[i]=dec%base+48; dec=int(dec/base);i--; } if (dec) result.value[i--]=dec+48; return result; } char * String::getValue() { return value; } main() { //Binary Input String char str1[33], str2[33]; cout << "Enter Binary String:"; cin >> str1; cout << "Enter Ternary String:"; cin >> str2; String bs(str1); cout << "Binary String =" << bs.getValue(); cout << "\nTernary Value =" << (bs.Base10ToN(bs.BaseNTo10(2),3)).getValue(); //ternary Input String String ts(str2); cout << "\n\nTernary String =" << ts.getValue(); cout << "\nBinary Value =" << (ts.Base10ToN(ts.BaseNTo10(3),2)).getValue() <<"\n"; return 0; }