Question

In: Computer Science

Converting from Decimal to Binary The algorithm you will use in this assignment to convert from...

Converting from Decimal to Binary The algorithm you will use in this assignment to convert from base 10 to base 2 is:

  • If the decimal number is zero, then the binary value is "0"
  • Otherwise, start with an empty String to contain your binary value
  • While your decimal number is not zero
    • Get the remainder of what your current decimal number would be when divided by 2.
    • Prepend this result to the front of your String.
    • Divide your decimal number by 2 and repeat.

So for example, the number 13 could be converted to a binary value as follows

  • Start with an empty String: ""
  • The number 13 != 0
    • 13 % 2 = 1
    • Prepend 1 to the front of our String: "1"+"" = "1"
    • 13 / 2 = 6 (Remember - integer division here, no fractions)
  • The number 6 != 0
    • 6 % 2 = 0
    • Prepend 0 to the front of our String "0" + "1" = "01"
    • 6 / 2 = 3
  • The number 3 != 0
    • 3 % 2 = 1
    • Prepend 1 to the front of our String "1" + "01" = "101"
    • 3 / 2 = 1
  • The number 1 != 0
    • 1 % 2 = 1
    • Prepend 1 to the front of our String "1" + "101" = "1101"
    • 1 / 2 = 0
  • The number 0 == 0
  • Our final result is: "1101"
  • Verify your result above by converting it back - 1*23 + 1*22 + 0*21 + 1*20 = 8 + 4 + 0 + 1 = 13.

Converting from Binary to Decimal To convert from a binary to a decimal representation, your code will need to take into account the place of each digit in the binary string. The algorithm we will use to do this for this project is:

  • Start with a value of 0 for your decimal number
  • Assign a value pow to be 1, the value of the power of the rightmost digit in your representation (i.e. 20)
  • For each digit in your binary representation, working from right to left on the String
    • Multiply the digit by your value for pow
    • Add that result to your decimal total
    • Multiply pow by 2
    • Repeat until all digits in the String have been processed

Here's an example of the number 1101 converted to a decimal number by applying the algorithm above

  • Start with result = 0, pow = 1
  • At pow 1
    • Multiply 1 by pow (20) = 1
    • result = 0 + 1 = 1
    • pow = pow * 2 = 2
  • At pow 2
    • Multiply 0 by pow (21) = 0
    • result = 1 + 0 = 1
    • pow = pow * 2 = 4
  • At pow 4
    • Multiply 1 by pow (22) = 4
    • result = 1 + 4 = 5
    • pow = pow * 2 = 8
  • At pow 8
    • Multiply 1 by pow (23) = 8
    • result = 5 + 8 = 13
    • pow = pow * 2 = 16 Since we have processed the left-most digit (i.e. index 0 in our String), we have our final result: 13. We can verify this by checking it with the algorithm for converting from binary to decimal above.

NOTE: For the method binaryToInt you are looking at the individual characters of a String. Remember that in order to use the numeric value of the character you MUST convert it to an integer value. Recall from previous projects that there are two methods that we've discussed for doing this - Character.getNumericValue() and Integer.parseInt(). The following two lines of code will convert the digit at index i in the string input into an integer value using getNumericValue():

char c = input.charAt(i);
int val = Character.getNumericValue(c);

And the following two lines of code do the same, using parseInt() instead:

String s = input.substring( i, i + 1 );
int val = Integer.parseInt(s);

IF YOU DO NOT EXPLICITLY CONVERT THE CHARACTER TO AN INTEGER VALUE YOU WILL NOT BE ABLE TO PASS TEST CASES. In addition, code that does not use one of these two methods to convert the character to an integer value will receive an additional deduction in points even if it does pass the test cases.

The two validation methods - validInteger and validBinary - each take a String as input and return true if the String is correctly formatted, false otherwise. Note that you will want to make use of the Character.isDigit(char c) method - this method returns true if the character it is passed as a parameter is a digit 0-9 and false otherwise. The following code segment shows how to use this method to print out a message telling the user whether or not the first character of their input is a digit.

Scanner in = new Scanner(System.in);
String str = in.nextLine();
char c = str.charAt(0);
if (Character.isDigit(c)) {
  System.out.println("That's a digit!");
}
else {
  System.out.println("That's NOT a digit!");
}

The skeleton for the code you need to implement starts here. Create a new class named BinaryNumbers and paste the skeleton below into it. Do not forget to update the header with the correct information about this program.

/**
 * ENTER A DESCRIPTION OF THIS PROGRAM HERE
 * @author YOUR NAME HERE
 * @version DATE HERE
 */
import java.util.Scanner;

public class BinaryNumbers {

    /**
     * Given a Scanner as input, prompt the user to enter an integer value. Use
     * the function validInteger below to make sure that the value entered is
     * actually a decimal value and not junk. Then return the value entered by
     * the user as an integer to the calling method.
     *
     * @param input
     *            A scanner to take user input from
     * @return a valid integer value read from the user
     */
    public static int promptForInteger(Scanner input) {
        System.out.print("Enter a positive integer value: ");
        String val = input.nextLine();
        while (!validInteger(val)) {
            System.out.println("ERROR - value must contain only digits");
            System.out.print("Enter a positive integer value: ");
            val = input.nextLine();
        }
        return Integer.parseInt(val);
    }

    /**
     * Given a Scanner as input, prompt the user to enter a binary value. Use
     * the function validBinary below to make sure that the value entered is
     * actually a binary value and not junk. Then return the value entered by
     * the user as an String to the calling method.
     *
     * @param input
     *            A scanner to take user input from
     * @return a String representing a binary value read from the user
     */
    public static String promptForBinary(Scanner input) {
        System.out.print("Enter a binary value: ");
        String val = input.nextLine();
        while (!validBinary(val)) {
            System.out.println("ERROR - value must contain only 1 and 0");
            System.out.print("Enter a binary value: ");
            val = input.nextLine();
        }
        return val;
    }

    /**
     * Given a String as input, return true if the String represents a valid
     * non-negative integer value (i.e. contains only digits). Returns false if the
     * String does not represent a non-negative integer value.
     *
     * Note that you must NOT use Exception Handling to implement this. If you
     * search on the net for solutions, that is what you will find but you
     * should not use it here - you can solve this using only what we have
     * discussed in class.
     *
     * Note too that your code does not need to worry about the number
     * represented being too large or too small (more than Integer.MAX_VALUE or
     * less than Integer.MIN_VALUE. Just worry about the constraints given above
     * for now (but for a challenge, try to figure out how to do it using only
     * what you have learned so far in class - it is not a simple problem to
     * solve.)
     *
     * @param value
     *            A String value that may contain an integer input
     * @return true if the String value contains an integer input, false
     *         otherwise
     */
    public static boolean validInteger(String value) {
        // TODO - complete this method

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return false;
    }

    /**
     * Given a String as input, return true if the String represents a valid
     * binary value (i.e. contains only the digits 1 and 0). Returns false if
     * the String does not represent a binary value.
     *
     * @param value
     *            A String value that may contain a binary value
     * @return true if the String value contains a binary value, false otherwise
     */
    public static boolean validBinary(String value) {
        // TODO - complete this method

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return false;
    }

    /**
     * Given a binary value, return an int value that is the base 10
     * representation of that value. Your implementation must use the algorithm
     * described in the Project write-up. Other algorithms will receive no
     * credit.  Note that this method assume the String value will be a 
     * String containing only 1s and 0s and its behavior is undefined for
     * other String values.
     *
     * @param value
     *            A String containing a binary value to convert to integer with
     *            only character '0' and '1' in it
     * @return The base 10 integer value of that binary in the String
     */
    public static int binaryToInt(String value) {
        // TODO - complete this method

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Given an integer value, return a String that is the binary representation
     * of that value. Your implementation must use the algorithm described in
     * the Project write-up. Other algorithms will receive no credit.  Note that
     * this method assumes that the integer parameter value will have a 
     * non-negative value, and the behavior of this method is undefined
     * for negative values.
     *
     * @param value
     *            A non-negative integer value to convert to binary
     * @return A String containing the binary representation of value
     */
    public static String intToBinary(int value) {
        // TODO - complete this method

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return "";
    }

    /**
     * Procedure to display a simple menu to the screen.
     */
    public static void displayMenu() {
        System.out.println("Please make a choice: ");
        System.out.println("1 - Integer to Binary Conversion");
        System.out.println("2 - Binary to Integer Conversion");
        System.out.println("3 - Quit");
    }

    public static void main(String[] args) {
        // Set up the scanner
        Scanner keyboard = new Scanner(System.in);
        // Display the menu and get the user choice
        displayMenu();
        int choice = promptForInteger(keyboard);

        // Loop until the user chooses to quit
        while (choice != 3) {
            if (choice == 1) {
                // User has chosen integer to binary
                int value = promptForInteger(keyboard);
                String binary = intToBinary(value);
                System.out.print("The integer value " + value);
                System.out.println(" is the binary value " + binary);
            } else if (choice == 2) {
                // User has chosen binary to integer
                String binary = promptForBinary(keyboard);
                int value = binaryToInt(binary);
                System.out.print("The binary value " + binary);
                System.out.println(" is the integer value " + value);
            } else {
                // User has chosen an invalid choice
                System.out.println("ERROR - Valid choices are 1, 2 or 3.");
            }
            System.out.println();
            // Display the menu again and get a new choice
            displayMenu();
            choice = promptForInteger(keyboard);
        }
        System.out.println();
        System.out.println("Goodbye!");
        keyboard.close();
    }

}

Here is an example of the program in operation once all four methods have been completed. As always, user inputs are marked in BOLD:

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 1
Enter a positive integer value: 35
The integer value 35 is the binary value 100011

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 2
Enter a binary value: 100011
The binary value 100011 is the integer value 35

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 3

Goodbye!

If the user makes an invalid selection, or puts in negative values for an integer to convert, the program will error and prompt for new values. Note that if you have written your methods correctly, this behavior will "just work" when you run the program:

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: -1
ERROR - value must contain only digits
Enter a positive integer value: 56
ERROR - Valid choices are 1, 2 or 3.

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 1
Enter a positive integer value: -56
ERROR - value must contain only digits
Enter a positive integer value: 13
The integer value 13 is the binary value 1101

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 2
Enter a binary value: 1034abc23
ERROR - value must contain only 1 and 0
Enter a binary value: 1011
The binary value 1011 is the integer value 11

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 4
ERROR - Valid choices are 1, 2 or 3.

Please make a choice: 
1 - Integer to Binary Conversion
2 - Binary to Integer Conversion
3 - Quit
Enter a positive integer value: 3

Goodbye!

Solutions

Expert Solution

Program:

/**
* ENTER A DESCRIPTION OF THIS PROGRAM HERE
* @author YOUR NAME HERE
* @version DATE HERE
*/
import java.util.Scanner;

public class BinaryNumbers {

   /**
   * Given a Scanner as input, prompt the user to enter an integer value. Use
   * the function validInteger below to make sure that the value entered is
   * actually a decimal value and not junk. Then return the value entered by
   * the user as an integer to the calling method.
   *
   * @param input
   *            A scanner to take user input from
   * @return a valid integer value read from the user
   */
   public static int promptForInteger(Scanner input) {
       System.out.print("Enter a positive integer value: ");
       String val = input.nextLine();
       while (!validInteger(val)) {
           System.out.println("ERROR - value must contain only digits");
           System.out.print("Enter a positive integer value: ");
           val = input.nextLine();
       }
       return Integer.parseInt(val);
   }

   /**
   * Given a Scanner as input, prompt the user to enter a binary value. Use
   * the function validBinary below to make sure that the value entered is
   * actually a binary value and not junk. Then return the value entered by
   * the user as an String to the calling method.
   *
   * @param input
   *            A scanner to take user input from
   * @return a String representing a binary value read from the user
   */
   public static String promptForBinary(Scanner input) {
       System.out.print("Enter a binary value: ");
       String val = input.nextLine();
       while (!validBinary(val)) {
           System.out.println("ERROR - value must contain only 1 and 0");
           System.out.print("Enter a binary value: ");
           val = input.nextLine();
       }
       return val;
   }

   /**
   * Given a String as input, return true if the String represents a valid
   * non-negative integer value (i.e. contains only digits). Returns false if the
   * String does not represent a non-negative integer value.
   *
   * Note that you must NOT use Exception Handling to implement this. If you
   * search on the net for solutions, that is what you will find but you
   * should not use it here - you can solve this using only what we have
   * discussed in class.
   *
   * Note too that your code does not need to worry about the number
   * represented being too large or too small (more than Integer.MAX_VALUE or
   * less than Integer.MIN_VALUE. Just worry about the constraints given above
   * for now (but for a challenge, try to figure out how to do it using only
   * what you have learned so far in class - it is not a simple problem to
   * solve.)
   *
   * @param value
   *            A String value that may contain an integer input
   * @return true if the String value contains an integer input, false
   *         otherwise
   */
   public static boolean validInteger(String value) {
       //run a loop to iterate through each character in the String
       for(int i = 0; i < value.length(); i++)
       {
           //get each character
           char ch = value.charAt(i);
           //return false if the character is not digit
           if(!(Character.isDigit(ch)))
               return false;
       }
       return true;
   }

   /**
   * Given a String as input, return true if the String represents a valid
   * binary value (i.e. contains only the digits 1 and 0). Returns false if
   * the String does not represent a binary value.
   *
   * @param value
   *            A String value that may contain a binary value
   * @return true if the String value contains a binary value, false otherwise
   */
   public static boolean validBinary(String value) {
       //run a loop to iterate through each character in the String
       for(int i = 0; i < value.length(); i++)
       {
           //get each character
           char ch = value.charAt(i);
           //return false if the character is not digit
           if(!(ch == '0' || ch == '1'))
               return false;
       }
       return true;
   }

   /**
   * Given a binary value, return an int value that is the base 10
   * representation of that value. Your implementation must use the algorithm
   * described in the Project write-up. Other algorithms will receive no
   * credit. Note that this method assume the String value will be a
   * String containing only 1s and 0s and its behavior is undefined for
   * other String values.
   *
   * @param value
   *            A String containing a binary value to convert to integer with
   *            only character '0' and '1' in it
   * @return The base 10 integer value of that binary in the String
   */
   public static int binaryToInt(String value) {
       int result = 0, pow = 1;
       //run a loop to iterate through the binary string from the last
       for(int i = value.length()-1; i >= 0; i--)
       {
           //get the value at index i
           char ch = value.charAt(i);
           int x = Integer.parseInt(ch + "");
           //Multiply the digit by your value for pow
           int y = pow * x;
           //Add that result to your decimal total
           result = result + y;
           //Multiply pow by 2
           pow = pow * 2;
       }
       return result;
   }

   /**
   * Given an integer value, return a String that is the binary representation
   * of that value. Your implementation must use the algorithm described in
   * the Project write-up. Other algorithms will receive no credit. Note that
   * this method assumes that the integer parameter value will have a
   * non-negative value, and the behavior of this method is undefined
   * for negative values.
   *
   * @param value
   *            A non-negative integer value to convert to binary
   * @return A String containing the binary representation of value
   */
   public static String intToBinary(int value) {
       String binaryValue = "";
       if(value == 0)
           return "0";
       else
       {
           while(value != 0)
           {
               int remainder = value % 2;
               binaryValue = remainder + binaryValue;
               value = value /2;
           }
           return binaryValue;
       }
   }

   /**
   * Procedure to display a simple menu to the screen.
   */
   public static void displayMenu() {
       System.out.println("Please make a choice: ");
       System.out.println("1 - Integer to Binary Conversion");
       System.out.println("2 - Binary to Integer Conversion");
       System.out.println("3 - Quit");
   }

   public static void main(String[] args) {
       // Set up the scanner
       Scanner keyboard = new Scanner(System.in);
       // Display the menu and get the user choice
       displayMenu();
       int choice = promptForInteger(keyboard);

       // Loop until the user chooses to quit
       while (choice != 3) {
           if (choice == 1) {
               // User has chosen integer to binary
               int value = promptForInteger(keyboard);
               String binary = intToBinary(value);
               System.out.print("The integer value " + value);
               System.out.println(" is the binary value " + binary);
           } else if (choice == 2) {
               // User has chosen binary to integer
               String binary = promptForBinary(keyboard);
               int value = binaryToInt(binary);
               System.out.print("The binary value " + binary);
               System.out.println(" is the integer value " + value);
           } else {
               // User has chosen an invalid choice
               System.out.println("ERROR - Valid choices are 1, 2 or 3.");
           }
           System.out.println();
           // Display the menu again and get a new choice
           displayMenu();
           choice = promptForInteger(keyboard);
       }
       System.out.println();
       System.out.println("Goodbye!");
       keyboard.close();
   }

}

Output:

Program Screenshot:


Related Solutions

Convert these numbers from Decimal to Binary 111: 66: 252 11 20 Convert these numbers from...
Convert these numbers from Decimal to Binary 111: 66: 252 11 20 Convert these numbers from Binary to Decimal 00110110 11111000 00000111 10101010 What is the Default Subnet mask of Class A IPV4 What is the Default Subnet mask of Class B IPV4 What is the Default Subnet mask of Class C IPV4 What is the CIDR notation or / short handwriting of Subnet masks: Class A: /?. Explain the reason Class B: /? Explain the reason Class C: /?...
Convert the decimal number, 315.56 into binary form?
Convert the decimal number, 315.56 into binary form?
i need to convert decimal to twos complement binary and then add the binary digits but...
i need to convert decimal to twos complement binary and then add the binary digits but I am unable to do it. I am only allowed to use string, can anyone help me out please. i need the code urgently. #include #include #include #include using namespace std; string reverse(string s) { string x = ""; for (long i = s.length() - 1; i >= 0; i--) { x += s[i]; } return x; } string twosComplementStringsAddition(string A, string B) {...
Convert the following binary number to dotted decimal format. 11000000100110010000100101011001
Convert the following binary number to dotted decimal format. 11000000100110010000100101011001
(6 pts) Convert the data representation given below • Convert 10110111 unsigned binary representation, to decimal...
(6 pts) Convert the data representation given below • Convert 10110111 unsigned binary representation, to decimal representation. • Convert 01100000101110000001010111111000 the binary representation to a hexadecimal representation. • Convert 0xBAAADA55 hexadecimal representation, to a binary representation. 2. (8 pts) Complete the following arithmetic operations in two’s complement representation. What are the values of the carry flag and the overflow flag? (Assume a six-bit system) • 31 + 11 • 13 – 15 • (-2) x (-16) • (-15) ÷ 5
Convert the binary numbers to decimal. Show a single sample calculation for the first number (10010010)....
Convert the binary numbers to decimal. Show a single sample calculation for the first number (10010010). 0111 1111 1001 0110 0101 1100 1100 0111
Code in C-language programming description about convert binary number to decimal number.
Code in C-language programming description about convert binary number to decimal number.
Convert the following unsigned numbers to the requested form: 01100001 binary to: hex, and also decimal...
Convert the following unsigned numbers to the requested form: 01100001 binary to: hex, and also decimal Hex: Decimal: b) 136 decimal to: hex, and also binary Hex: Binary:
Write a program to convert the input numbers to another number system. 1. Decimal to Binary...
Write a program to convert the input numbers to another number system. 1. Decimal to Binary 2. Binary to Decimal 3. Hexadecimal to Decimal 4. Decimal to Hexadecimal 5. Binary to Hexadecimal 6. Hexadecimal to Binary The user will type in the input number as following: Binary number : up to 8 bits Hexadecimal number: up to 2 bytes Decimal number: Less than 256 As a result, print out the output after the conversion with their input numbers. The program...
(a) Convert the decimal numbers, 70 and -26 to binary in the signed 2’s complement system....
(a) Convert the decimal numbers, 70 and -26 to binary in the signed 2’s complement system. Make sure there are enough digits in the results to be able to perform arithmetic operations with these two numbers. (b) Perform in the signed 2’s complement system, (+70) + (-26) (c) Perform in the signed 2’s complement system, (-70) - (-26) (d) Perform in the signed 2’s complement system, (+70) + (+26)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT