Reputation: 13
Im trying to make a program that converts binary to decimal but having the needs to show the process of the convertion
Enter a binary number: 10110
1*(2^4) + 1*(2^2) + 1*(2^1)
the decimal equivalent of 10110 is: 22
but instead the value of the counter in the middle of the loop fails to decrease, leading to this
this is my current code
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
int bin, dec = 0, remainder, num, base = 1,counter=0,counter2=0, constnum;
cout << "Enter the binary number: ";
cin >> num;
bin = num;
constnum = num;
while(bin > 0)
{
bin=bin/10;
counter2++;
}
while (num > 0)
{
if (num % 10 == 1) {
cout << " 1*(2^" << counter2 << ") +";
counter2--;
}
else if(num % 10 == 0) {
counter2--;
}
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
}
cout << "\nThe decimal equivalent of " << constnum << " : " << dec << endl;
return 0;
}
Upvotes: 0
Views: 70
Reputation: 7552
As already pointed out, you are calculating and displaying the result in different orders. I suggest that you store the result and display it later. Something like:
#include <sstream>
....
int pos = 0;
string res;
while (num > 0) {
if (num % 10 == 1) {
stringstream out;
out << "1*(2^" << pos << ") + ";
res = out.str() + res;
}
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
pos++;
}
int len = res.length();
// to remove the last '+'
if (len >= 3) {
res = res.substr(0, len - 3);
}
cout << res;
Upvotes: 0
Reputation: 1
you should wirte the process in ascendant order, instead of descendant, this is to match your algorithim, which is in ascendant order
So, in your last while, instead of this:
if (num % 10 == 1) {
cout << " 1*(2^" << counter2 << ") +";
counter2--;
}
else if(num % 10 == 0) {
counter2--;
}
you should do this:
if (num % 10 == 1) {
cout << " 1*(2^" << counter << ") +";
counter++;
}
else if(num % 10 == 0) {
counter++;
}
also, if you follow my recommendation, you may erase your first while:
while(bin > 0)
{
bin=bin/10;
counter2++;
}
because is no longer needed
Upvotes: 0
Reputation: 264471
Just use a bit set:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<32> val;
std::cin >> val;
std::cout << val.to_ulong() << "\n";
}
Upvotes: 1