Using C++ (specifically stacks structures of C++), write a converter that conver
ID: 3801872 • Letter: U
Question
Using C++ (specifically stacks structures of C++), write a converter that converts a binary to decimal.
This is the code I have so far but I can't get it to work:
/* for this program, the algorithm I am trying to use for binary-decimal conversion is to
convert each digit by different powers of 2, and then add them up to get the decimal value.
For example: binary 1101 = 1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 = 1 + 0 + 4 + 8 = decimal 13
I am still confused on how to use push, pop, and top.*/
#include <iostream>
#include <stack>
#include <math.h>
using namespace std;
int main()
{
stack<int> intStack;
cout << "the binary is 1101, convert to decimal please?" << endl;
intStack.push(1);
intStack.push(0);
intStack.push(1);
intStack.push(1);
int base = 2; // base of 2
int power = 0; // power of 2
int decimal = 0; // the decimal that binary is converted to
while (!intStack.empty())
{
decimal = intStack.top() * (base^power);
power++;
intStack.pop();
cout << "The decimal is: " << decimal << endl;
}
}
Explanation / Answer
#include <iostream>
#include <stack>
#include <math.h>
using namespace std;
int main()
{
stack<int> intStack;
cout << "the binary is 1101, convert to decimal please?" << endl;
//You are adding the bits from least significant end
intStack.push(1);
intStack.push(0);
intStack.push(1);
intStack.push(1);
int base = 2; // base of 2
int power = 0; // power of 2
int decimal = 0; // the decimal that binary is converted to
//Number of bits in the binary string
int n = 4;
while (!intStack.empty())
{
//decimal variable should be added to the previous decimal and (base^power) calculates the xor of base and power, but not exponential
//Since you are retrieving bits from the most significant end (From left), you should use pow(base,n-power-1), but not pow(base,power)
decimal = decimal + intStack.top() * pow(base,n-power-1);
power++;
intStack.pop();
}
cout << "The decimal is: " << decimal << endl;
}
OUTPUT :
the binary is 1101, convert to decimal please?
The decimal is: 13
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.