#include <iostream>
#include <math.h>
usingnamespace std;
int main()
{
int bin, dec = 0, remainder, num, base = 1;
cout << "Enter the binary number: ";
cin >> num;
bin = num;
while (num > 0)
{
rememainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
}
cout << "Decimal Value" << bin << " : " << dec << endl;
return 0;
}
In your code, the first time you get the last digit, that's 2^0.
In your code, the second time you get the last digit, that's 2^1.
In your code, the third time you get the last digit, that's 2^2.
In your code, the fourth time you get the last digit, that's 2^3.
In your code, the fifth time you get the last digit, that's 2^4.
And so on.
So each time you get the last digit, if it's a 1, put: 1*(2^ whichever) +
on the front of the output string.
in this block what variable is 'whichever'
should i use a forloop to counter the exponential increase while checking if its a 0 or a 1 with if condition?
#include <iostream>
#include <math.h>
usingnamespace std;
int main()
{
int bin, dec = 0, remainder, num, base = 1,counter = 0;
cout << "Enter the binary number: ";
cin >> num;
bin = num;
while (num > 0)
{
remainder = num % 10; //get the last digit of the input
dec = dec + remainder * base;
base = base * 2;
num = num / 10;
counter++;
if (num % 10 == 1)
{
cout << "1*(2^" << counter << ") ";
}
}
cout << "\nThe decimal equivalent of " << bin << " : " << dec << endl;
return 0;
}
In your code, the first time you get the last digit, that's 2^0.
In your code, the second time you get the last digit, that's 2^1.
In your code, the third time you get the last digit, that's 2^2.
In your code, the fourth time you get the last digit, that's 2^3.
In your code, the fifth time you get the last digit, that's 2^4.
And so on.
So each time you get the last digit, if it's a 1, put:
1*(2^ whichever) +
on the front of the output string.
Im sorry but i dont get it,
i cant store a counter which is an integer inside a string variable for the output
what do you mean in front of the output string?
string output; // Create a new string. Blank
// Each time round the loop, put new letters on the front
output = string("+ 1*(2^") + to_string(counter) + ") " + output;
// when all done, remove leading '+' from string and output the string
you can do a lookup table of all 255 byte combinations without using to-string. Just be endian aware. You can do it off nibbles if you prefer, its just a bit more weird, might use a bit field struct over a byte to do it..