So I want to write a program that takes a binary value as input and converts it into gray code and vice versa.
Here's what I originally wrote:
#include <iostream>
using namespace std;
int main()
{
int Choice;
bool g0,g1,g2,g3,b0,b1,b2,b3;
cout<<"For Binary To Gray Code Enter 1." << endl <<"For Gray Code to Binary Enter 2." << endl;;
cin>>Choice;
if(Choice==1)
{
cout<<"Enter the Binary Bits." << endl;
cin>>b0>>b1>>b2>>b3;
cout<<"Orginal Binary Form: "<<b3 <<b2 <<b1 <<b0 << endl;
g3=b3;
g2=b3^b2;
g1=b2^b1;
g0=b1^b0;
cout<<"Converted Gray Code Form: "<<g3 <<g2 <<g1 <<g0 << endl;
}
else if(Choice==2)
{
cout<<"Enter The Gray Code Bits." << endl;
cin>>g0>>>g1>>g2>>g3;
cout<<"Original Gray Code Form: "<<g3 <<g2 <<g1 <<g0 << endl;
b3=g3;
b2=b3^g2;
b1=b2^g1;
b0=b1^g0;
cout<<"Converted Binary Form: "<<b3 <<b2 <<b1 <<b0 << endl;
}
return 0;
}
Now this works for 4 bits but
I want something that determines the size of the entered binary/gray code by the user during runtime.
I did a bit of research and found out about using vectors in such a case but since in college we just started C++ I'm not familiar with vectors or even arrays. Is there anything else that I can use to achieve it? If not, can anyone tell me how vectors can be used for it?
Secondly I want to take the input in a single line without spaces.
Example:
1011
rather than1 0 1 1
or taking input for each bit in a separate line.Now I also realize that I won't be able to know the no. of bits in advance so the bits formula I used to achieve XOR operation would also be changed. Is it possible to declare a binary and gray code
bool
variable and somehow perform the XOR operation on those variables rather the individual bits using simpler statements, nothing complex?