Binary Nums
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?
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. 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()). |
| |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SolutionThe greatest ways to start a problem is to divide it into smaller problems. Clearly, the main problem to solve is converting binary numbers to decimal numbers. Input using the scanner class and looping for more input are the other two sub-problems. Determine how to Convert from Binary Numbers to Decimal NumbersSo you don't know how to convert binary numbers to decimal numbers. That is fine. You can figure it out. To solve the problem, we will initially forget about writing good java code, and instead use anything simpler. We can draw diagrams, write equations, and write pseudocode. We can always write java code after we understand how to solve the problem. The first thing to do is gather information from the problem specification. In it we were told:
1 * 2^6 + 0 * 2^5 + 1 * 2^4 + 1 * 2^3 + 0 * 2^2 + 0 * 2^1 + 1 * 2^0 = 89 If we look at this carefully, we see that the right most digit of the binary number is multiplied by 2^0. The second left most digit is multiplied by 2^1. The digit to the right of that is multiplied by 2^2 and so on. Finally, all those products are summed up. However, we need to make sure we are correct. Let's check that we understand by converting some of the following numbers from binary to decimal. 0, 1, 10, 11, 101, 1000, 1101, 10101 Now, try to write some pseudocode to explain how we solved this problem. We will later shape this into Java code. 1. take the rightmost digit, if it is a 1, multiply it by 2 to the power of the current exponent and add it to the sum. 2. do the same with digits to the left of the rightmost digit. A little bit more thinking shows we need to tell what sum, and what exponent to start at. Anything multiplied by zero is zero, so we can simplify the pseudocode. Let's also add variables for clarity. exponent = 0 sum = 0 take the rightmost digit ''d'', sum = sum + d * 2^exponent do the same with digits to the left of the rightmost digit.
Convert to Java-like PseudocodeHow do I extract the rightmost digit?In Java, you have some basic arithmetic operators, you can multiply (using *), divide (using /), add (+), subtract (-), and get the remainder (%). If you can define what the rightmost digit is using the above operations you can easily determine what it is. The rightmost digit of a number is the exact same thing as the remainder of a number divided by 10. For example, the remainder of 26 divided by 10 is 6. In Java, we would write 26 % 10 to do the same operation. How do I ignore the rightmost digit?So you want to convert 321 to 32. Recall, that in Java the division of two integers ignores any fractions. So 3/2 =1, in Java code although it equals 1.5 in regular math. The way java calculates the quotient is called integer division. To chop off the rightmost digit, we simply do integer divide by 10. In Java, we would write 26 /10 and the result would be 2.
Transform the Pseudocode into Java CodeYou can continue improving the pseudocode slightly until you have replaced much of the English instructions with Java-like code. Here is an example of my result. exponent = 0 sum = 0 while (binaryNum!= 0) { rightmost = binaryNum % 10 //right most digit sum = sum + rightmost * 2^exponent binaryNum = binaryNum / 10 //do the same with the digits to the left of the rightmost digit } Now that you have some code, let's make sure that it is sound. Let's run it through the compiler. Create the Structure of the ProgramNow create a Java file. Define the class in a Java file. Name the file the same name as the class name plus the ".java" extension. Define the main method. The following code shows the result of these steps. public class BinaryNum { public static void main(String[] args) { } } Test your CodeTake the code for converting numbers, and paste it into the main method. Then compile it and fix any errors. You may need to add semicolons, and declare variables. You will need to add an output statement so you can test your results. As for input, just set the binaryNum variable in the code for now (this is called hardcoded input). public class BinaryNum { public static void main(String[] args) { int binaryNum = 101; //hardcoded input int exponent = 0; int sum = 0; while (binaryNum!= 0) { rightmost = binaryNum % 10 //right most digit sum = sum + rightmost * 2^exponent; binaryNum = binaryNum / 10; //do the same with the digits to the left of the rightmost digit } System.out.println(binaryNum + "in decimal is " + sum); } } Fix your CodeYou are likely to discover small syntactical errors when you try to compile your code. After successfully compiling your code you might find that the program gives incorrect output. In such a situation, a computer scientist needs to accept that their code is incorrect, and try to determine the problem. However, it can be difficult to see the mistake if the same type of thinking that produced the error is used to see the error. You need to think like the machine to see the error. Go through your code line by line, and determine what went wrong. After fixing my code I had the following: public static void main(String[] args) { int binaryNum = 101; //hardcoded input int exponent = 0; int sum = 0; int rightmost; int copyOfBinNum = binaryNum; while (copyOfBinNum!= 0) { rightmost = copyOfBinNum % 10; //right most digit sum = sum + rightmost * 2^exponent; copyOfBinNum = copyOfBinNum / 10; //do the same with the digits to the left of the rightmost digit } System.out.println(binaryNum + " in decimal is " + sum); } Now test your code with different values for binaryNum. Don't forget to recompile after changing your code. Once you are satisfied, that your code correctly converts binary numbers to decimal numbers move to the next step. Determine how to input the numberYou'll want to store the number as a long. A long is an extra long integer. It can store larger integers than regular int.
Import the Scanner ClassInclude the following line at the top of the Java file, before the class definition. import java.util.Scanner; Declare and Instantiate the Scanner ClassBecause we want to read from the terminal, instantiate the scanner class with System.in as a parameter. Scanner kbd = new Scanner(System.in); Use the correct methodUse nextLong() method in order to read in a long from the terminal. binaryNumber = kbd.nextLong();
Add a LoopFrom the program specification, we know that we need a loop: Use a loop so the user can continue to input binary numbers until they input -1 , then exit. Determine the Kind of LoopWe could use a for-loop or a while-loop. One rule to follow is that a for-loop is best used if you can determine in advance how many times the loop will run. In this case, we do not know how many times the user will input binary numbers. Therefore we should use a while loop. while(/* Put termination condition here */) { } Determine the Termination ConditionFrom the program specification, we know we need to stop when the user inputs -1. Expressed using the word while, we need to continue prompting for input while the input is not -1. while(binaryNumber != -1) { } | ||||||||||||||||||||||||||
Code |