You are using a version without Ads of this website. Please, consider donating:

Convert a binary number into a decimal number

closed account (4wCjE3v7)
Here's the part of the codes where I tried to use boolean expression:
 ``1234567891011121314151617181920212223`` ``````#include using namespace std; int main() { int num; cout << "8-bit Binary Number="; cin >> num; bool valid = true; . . . . . . . . . if (valid) { cout << "Decimal Number = " << sum; } }``````

May I know that how can I get started with the body?

this code converts a binary number to a decimal one.
you can use it as a function under your condition ( => ` if(valid) ` <= )

 ``123456789101112131415`` ``````#include #include #include using namespace std; int main() { string bin; cin >> bin; int dec = 0; reverse(bin.begin(), bin.end()); for (int i = 0; i < bin.size(); ++i) { dec += (int(bin[i]) - 48)*pow(2, i); } cout << dec; return 0; }``````
Last edited on
I would use a string instead of an int for num.
Step 1. Check if you have 8 digits
Step 2. Check if all digits are 0 or 1
Step 3. Calculate sum (inside if(valid){ ... })
closed account (4wCjE3v7)
Hi, mokhi64,
Thanks for your suggestions up there, but I'm just a beginner for c++ and have not gone to this extent yet. There are some code you written down I still understand yet.
So, may I know that how can I continue my code above from line 10 to if (valid)? thanks
Yo Vampire ,
is this your assignment for programming subject or something?
Can you convert from base 2 to base 10 manually?
If not each column starting from the right has double the value of the previous column. The first column has a value of 1, the next 2, the next 4 then 8,16,32,64,128,256,512,1024,2048.... and so on.
To convert to base 10 from base 2 : 01110101110000110100111.
you would get (starting from the right hand end) of the binary number:
1*1+1*2+1*4+0*8+0*16+1*32+0*64+1*128...and so on.
Now you need to write some code which will perform similarly; and post again if you have difficulties.
Topic archived. No new replies allowed.