Given a binary number ,help Von Neuman to find out its decimal representation. For eg 000111 in binary is 7 in decimal. not able to make a approach
Binary number prblm
Hey @zaid.shamshi4
This is simple binary to decimal conversion what u are not able to understand here.
How to convert binary to decimal
For binary number with n digits:
dn-1 … d3 d2 d1 d0
The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n):
decimal = d 0×20 + d 1×21 + d 2×22 + …
Example
Find the decimal value of 111001:
binary number: | 1 | 1 | 1 | 0 | 0 | 1 |
---|---|---|---|---|---|---|
power of 2: | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 |
111001 = 1â‹…2^5+1â‹…2^4+1â‹…2^3+0â‹…2^2+0â‹…2^1+1â‹…2^0 = 57
000111= 0â‹…2^5+0â‹…2^4+0â‹…2^3+1â‹…2^2+1â‹…2^1+1â‹…2^0 = 7
Input binary no as string/char array
and to converte each digit to 0 or 1 use
x-‘0’
For example
string s;
cin>>s;//s is now 000111
for(int i=s.length()-1;i>=0;i--){//traverse from right to left
int digit =s[i]-'0';//converte char representation of 0 or 1 to integer digit 0 or 1
}
Refer to this if req
#include <iostream>
using namespace std;
int main() {
string s;
cin>>s;
int value=0;//to store final value
int pow=1;// for powers of 2
for(int i=s.length()-1;i>=0;i--){//traverse from right to left
int digit =s[i]-'0';//converte char representation of 0 or 1 to integer digit 0 or 1
value += digit*pow;
pow=pow*2;
}
cout<<value;
return 0;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.