Hi guys, I wanna convert binary numbers to decimal without using #include<cmath>. The code I have now can convert most of the "1" and "0" into correct decimal, however I try to input numbers like 12111211 it suppose to be invalid but it show some weird numbers. I would like to perform a number test before the convert operation start, but I had no idea how to do it. Here is my code
Firstly i think num should be declared as std::string instead of int for generality. int cannot take large numbers as input. If you decide to increase your number of bits, then int will fail.
Also, your check for a valid number is incorrect. You are checking only for the 1st digit to be a binary number and that the number should be less than 11111111. This means that a number like 561 would be wrongly treated as a valid binary number.
Modify your code to something like the following. (haven't tested it, but it should give you an idea)
The original question actually start from the line bool valid = true, so I could not include string into it and do this without string method. I get the idea how to test the number, but I failed to test every number which bugged me for few days just for the exact condition.
Thanks for the idea, I will try to modify right away.
The problem I see with getting the input as a numeric type rather than a character string, is that this code is doing a conversion of its own:
1 2 3
cout << "8 bit Binary Numbers = " ;
cin >> num;
At the prompt, the user types a string of characters. the cin >> num statement takes those characters, treat them as decimal digits and translates and stores the resulting input as a binary value in the variable num.
The integer type uses an internal binary representation in order to store the value. That forces the code to to an extra step of converting the binary value into decimal and makes the code more complicated than necessary:
x = y%10; // get decimal digit from binary value
y = y/10;
It also limits the range of values which the user is able to input, as the number of decimal digits is constrained.