Print Friendly and PDF
(Printing the Decimal Equivalent of a Binary Number) Input an integer containing only 0s and 1 s (i.e., a “binary” integer) and print its decimal equivalent. Use the modulus and division operators to pick off the “binary” number’s digits one at a time from right to left. Much as in the decimal number system, where the rightmost digit has a positional value of 1 , the next digit left has a positional value of 1 0, then 1 00, then 1 000, and so on, in the binary number system the rightmost digit has a positional value of 1 , the next digit left has a positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted as 2 * 1 00 + 3 * 1 0 + 4 * 1 . The decimal equivalent of binary 1 1 01 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8, or 1 3. [Note: To learn more about binary numbers, refer to Appendix D.] Solution:
(Printing the Decimal Equivalent of a Binary Number) Input an integer containing only 0s and 1 s (i.e., a “binary” integer) and print its decimal equivalent. 

Use the modulus and division operators to pick off the “binary” number’s digits one at a time from right to left. Much as in the decimal number system, where the rightmost digit has a positional value of 1 , the next digit left has a positional value of 1 0, then 1 00, then 1 000, and so on, in the binary number system the rightmost digit has a positional value of 1 , the next digit left has a positional value of 2, then 4, then 8, and so on. 

Thus the decimal number 234 can be interpreted as 2 * 1 00 + 3 * 1 0 + 4 * 1 . The decimal equivalent of binary 1 1 01 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8, or 1 3. 

[Note: To learn more about binary numbers, refer to Appendix D.]

Solution:

#include < cstdio>
#include < cstdlib>
#include < iostream>
using namespace std;
int main()
{
int bin;
int dec = 0;
int control =1;
cout << "Enter number in binary format: ";
cin >> bin;
while( bin >= 1 )
{
dec = dec + (bin%10) *control;
bin /= 10;

control *= 2;
//check values after each iteration
cout << "dec: " << dec << " bin: " << bin << " control: " << control << endl;
}
cout << "Decimal is " << dec << endl;
//for pause
system("PAUSE") ;
return main() ;
}
zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

0 comments: