check my binary to decimal code please.

i'm trying to convert a binary number into a decimal but i get big numbers for some reason.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() 
{
        char binary[4];
	double decimal;
	int dec0, dec1, dec2, dec3;
	cout << "Enter a 4 digit binary number: ";
	cin.getline(binary, 4, '\n');
	dec0 = 1 * binary[0];
	dec1 = 2 * binary[1];
	dec2 = 4 * binary[2];
	dec3 = 8 * binary[3];
	decimal = dec0 + dec1 + dec2 + dec3;
	cout << "\nDecimal = " << decimal << endl;
        system("pause");
        return 0;
}


the above code doesn't work but i want to basically make it so it works something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
	char binary[4];
	double decimal;
	int dec0, dec1, dec2, dec3;
	int sol0, sol1, sol2, sol3;
	cout << "Enter a 4 digit binary number: ";
	cin >> dec3 >> dec2 >> dec1 >> dec0;
	sol0 = dec0 * 1;
	sol1 = dec1 * 2;
	sol2 = dec2 * 4;
	sol3 = dec3 * 8;
	decimal = sol0 + sol1 + sol2 + sol3;
	cout << "\nDecimal = " << decimal << endl;



	system("pause");
	return 0;
}
Last edited on
Probably because you're trying to store an int (4 bytes) in a char (1 byte).

edit:
Found a method in the string class that allows you to convert a string to an int. You can also specify the base.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using std::cout; using std::cin; using std::endl;
using std::string; using std::stoi;

int main() 
{
        string binary = "";
	int decimal = 0;
	
	cout << "Enter a 4 digit binary number: ";
	cin >> binary;
	
	decimal = stoi(binary, nullptr, 2);
	
	cout << "\nDecimal = " << decimal << endl;
	
    return 0;
}
Last edited on
appreciate the reply/help.
My professor hasn't taught us how to use stoi, or nullptr so i can't use those.
the second code is what i want to do but i want to do it without the spaces. (cin >> dec3 >> dec >> ect.)
closed account (48T7M4Gy)
Don't double post on same problem.
Last edited on
Topic archived. No new replies allowed.