So i have to convert two's complement binary to decimal in C++ by first inserting the number of bits user wants to use 1 by one for example: Bits: 4
Insert the bit in position 3: 1
Insert the bit in position 2: 0
Insert the bit in position 1: 0
Insert the bit in position 0: 0
I have done the code for this using an array and then using for to store a[i]. I'm stuck and i dont know what to do to convert it to decimal. I would appreciate any help thanks.
int main() {
int n;
cout << "Bits: " << endl;
cin >> n;
while (n < 2) {
cout << "Error! " << endl;
cout << "Bits: " << endl;
cin >> n;
}
int a[10000];
for (int i = n; i > 0; i--) {
cout << "Insert the bit in position " << i - 1 << ": " << endl;
cin >> a[i];
while (a[i] != 0 && a[i] != 1) {
cout << "Error! " << endl;
cout << "Insert the bit in position " << i - 1 << ": " << endl;
cin >> a[i];
}
}
int choice;
cout << "Operation: " << endl;
cout << " 0 - Print binary: " << endl;
cout << " 1 - Convert in decimal: " << endl;
cout << "Choice: ";
cin >> choice;
cout << endl;
switch (choice) {
case 0:
cout << "Binary number: ";
for (int i = n; i > 0; i--)
cout << a[i];
cout << endl;
break;