Difference between revisions of "Binary Nums"
ElsanussiM (Talk | contribs) m (corrected formula in problem definition (added exponent symbols)) |
ElsanussiM (Talk | contribs) m (grammatical correction of first program specification) |
||
Line 60: | Line 60: | ||
=Program Specifications= | =Program Specifications= | ||
<ul> | <ul> | ||
− | <li>Write a program that takes input as an integer, interprets it as a binary number, and prints out its value | + | <li>Write a program that takes input as an integer, interprets it as a binary number, and prints out its value as a decimal number. |
</li><li> Get input using Scanner. | </li><li> Get input using Scanner. | ||
</li><li> Use integer division and remainder to extract digits from the input binary number. | </li><li> Use integer division and remainder to extract digits from the input binary number. |
Revision as of 10:19, 27 March 2011
Back to the Case Studies homepage
ProblemAs you may know, computers work on the binary system. In this system, numbers are written using only 0s and 1s. In this question, you’ll write a program to convert binary numbers to normal (decimal) numbers. How are all numbers represented in 0s and 1s?
Here are the first few numbers written in both decimal (normal) notation and binary:
Suppose we have a binary number (a sequence of zeroes and ones) and we want to convert it to a decimal number. To do this, we multiply the digit (0 or 1) in each position of the number by an increasing power of two the further we move left. So the value of the binary number 1011001 is 1 * 2^6 + 0 * 2^5 + 1 * 2^4 + 1 * 2^3 + 0 * 2^2 + 0 * 2^1 + 1 * 2^0 = 89
Program Specifications
OutputUse System.out for output. Follow the format of the output shown above. Hand-inSave your file using the naming conventions described in the beginning of the assignment. Upload your file using the web-based hand-in tool. Submit three sets of data using the following input:
You may notice that your program fails for large numbers. That's because of integer overflow. If you would like to get your program to work for larger binary numbers, replace int with long in your program (including using the Scanner method nextLong()). |
| |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Solution | ||||||||||||||||||||||||||
Code |