Question

Implement a Java method named addBinary() that takes two String arguments (each representing a binary value)...

Implement a Java method named addBinary() that takes two String arguments (each representing a binary value) and returns a new String corresponding to the result of performing binary addition on those arguments. Before you begin, if one of the arguments is shorter than the other, call your pad() method from the previous step to extend it to the desired length.

Note: ped() method is

public static String pad(String input, int size)
{
if(input.length()>=size) {
return input;
}
String a = "";
for(int i=0; i < (size - input.length()); i++ )
a += "0";
return (a + input);

}

Define a Java method named toTwosComplement() that takes two integer arguments: a base 10 value to be translated into two’s complement representation, and a second integer representing the length of the two’s complement representation. The method converts the first argument into a String (containing only 1s and 0s) of the specified length and returns that String.

Use the following algorithm to convert an integer value into two’s complement form:

a. If the integer value is positive or zero:

i. Translate the integer value into a binary string using repeated division by 2 (i.e., using the algorithm you discussed in class).

ii. Use pad() to extend the binary string to the required length.

b. Otherwise (meaning that the integer value is negative):

i. Translate the absolute value of the integer into a binary string (for example, given the integer value -6, translate 6 into a binary string).

ii. Use pad() to extend the binary string to the required length.

iii. Negate the binary string by inverting its value and adding1 (using binary addition):

1. To invert a binary string, create a new String of the same length where all the 1s have been replaced by 0s and all the 0s have been replaced by 1s. For example, inverting “0010101” would produce the string “1101010”.

2. Add the binary value 1 to the inverted string from the previous step using your binaryAdd() method.

iv. If the negated binary string is greater than the specified length (due to an extra carry bit), remove the leading character (bit). For example, suppose that we wish to convert -13 to 6-bit two’s complement representation (meaning that our method call is toTwosComplement(-13, 6)). Positive 13 in binary is “1101”; padding this to a length of 6 gives us “001101”. Since the original number was negative, we invert the bits of the padded binary representation to get “110010”. Adding 1 with binary addition gives us a final value of “110011” (if we had exceeded 6 bits, we would have returned only the last 6 bits of the result).

4. Finally, write a small Java program that tests your methods via two tasks: a. Read in two binary strings from the user, add them using binary addition, and print the result. For example, 110 + 1101 = 10011. Likewise, 1001 + 1111 = 11000. b. Read in a decimal (base 10) integer value from the user and a desired length in bits. Your program should calculate and display the two’s complement representation of the original integer value. For example, 34 in 8-bit two‘s complement is 00100010, while -305 in 10-bit two’s complement is 1011001111.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Scanner;

public class BinaryOperation {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter first binary number");
        String firstBinary = scan.nextLine();
        System.out.println("Enter second binary number");
        String secondBinary = scan.nextLine();
      
        String addition = addBinary(firstBinary, secondBinary);
        System.out.println("Addition ="+addition);
      
        System.out.println("Enter decimal integer number : ");
        int number = Integer.parseInt(scan.nextLine());
      
        System.out.println("Enter desired length bits : ");
        int bits = Integer.parseInt(scan.nextLine());
      
        String twosComp = toTwosComplement(number, bits);
        System.out.println("Two's complement of the number "+number+", in "+bits+"-bits ="+twosComp);
    }
    public static String pad(String input, int size)
    {
        if(input.length()>=size) {
            return input;
        }
        String a = "";
        for(int i=0; i < (size - input.length()); i++ )  
            a += "0";
        return (a + input);

    }
    public static String addBinary(String binary1, String binary2)
    {
        String output="";
        if(binary1.length() == binary2.length())
        {
            int digitSum = 0;
          
            for(int i= binary1.length() - 1; i>=0;i--)
            {
                //calculate digit sum
                digitSum += binary1.charAt(i)-'0' + binary2.charAt(i)-'0';
              
                output = (char)(digitSum % 2 + '0') + output;
              
                //calculate the carry
                digitSum /= 2;
              
            }
            if(digitSum > 0)
                output = (char)(digitSum + '0') +output;
        }
        else if (binary1.length() < binary2.length())
        {
            binary1 = pad(binary1, binary2.length());
            return addBinary(binary1, binary2);
        }
        else if (binary1.length() > binary2.length())
        {
            binary2 = pad(binary2, binary1.length());
            return addBinary(binary1, binary2);
        }
          
        return output;
    }
  
    public static String toTwosComplement(int number, int bits)
    {
        String output = "";
      
        //If the integer value is positive or zero:
        if(number >= 0)
        {
            //Translate the integer value into a binary string using repeated division by 2
            while(number > 0)
            {
                output = number % 2 + output;
                number /= 2;
            }
            //Use pad() to extend the binary string to the required length.
            output = pad(output, bits);
        }
        //Otherwise (meaning that the integer value is negative):
        else
        {
            number *= -1;
            String binary="";
            //Translate the integer value into a binary string using repeated division by 2
            while(number > 0)
            {
                binary = number % 2 + binary;
                number /= 2;
            }
            //Use pad() to extend the binary string to the required length.
            binary = pad(binary, bits);
          
            //negate the binary string
            for(int i=0;i<binary.length();i++)
            {
                if(binary.charAt(i)=='0')
                {
                    output += "1";
                }
                else if(binary.charAt(i)=='1')
                {
                    output += "0";
                }
            }
            //Add the binary value 1 to the inverted string
            output = addBinary(output, "1");
            // If the negated binary string is greater than the specified length
            //(due to an extra carry bit), remove the leading character (bit)
            if(output.length() > bits)
                output = output.substring(1);
        }
        return output;
    }
}

Add a comment
Know the answer?
Add Answer to:
Implement a Java method named addBinary() that takes two String arguments (each representing a binary value)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a C++ program that simulate a menu based binary number calculator.You don't have to write the main part of the...

    Write a C++ program that simulate a menu based binary number calculator.You don't have to write the main part of the program just the two functions for my C++ program. I wanted to post the sample code from my class but it won't allow me it's too long. This calculate shall have the following five functionalities: Provide sign extension for a binary number Provide two’s complement for a binary nunber string signed_extension(string b);              // precondition: s is a string that...

  • Create a program (java): that reads a 8-bit String input, must be read in as such....

    Create a program (java): that reads a 8-bit String input, must be read in as such. Then convert that string of 1s and 0s to decimal as if it were encoded using the following representations: Unsigned 1's Complement 2's Complement Q(4.4) (2's complement) 1 bit (sign) - 3 bits (exponent: use bias) - 4 bits (significand), implied binary point w/ 1. Also check for 0.... Do not use helper functions, must be done iterating string and modifying an int/long value....

  • Using Java: 1. Recursive Multiplication Write a recursive function that accepts two arguments into the parameters...

    Using Java: 1. Recursive Multiplication Write a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. Remember, multiplication can be performed as repeated addition as follows: 5×6=6+6+6+6+6 2. Recursive findings Write a recursive boolean method named reFinding. The method should search an array for a specified value, and return true if the value is found in the array, or false if the value is not found in...

  • JAVA PROG HW Problem 1 1. In the src −→ edu.neiu.p2 directory, create a package named...

    JAVA PROG HW Problem 1 1. In the src −→ edu.neiu.p2 directory, create a package named problem1. 2. Create a Java class named StringParser with the following: ApublicstaticmethodnamedfindIntegerthattakesaStringandtwocharvariables as parameters (in that order) and does not return anything. The method should find and print the integer value that is located in between the two characters. You can assume that the second char parameter will always follow the firstchar parameter. However, you cannot assume that the parameters will be different from...

  • Rational Number *In Java* A rational number is one that can be expressed as the ratio...

    Rational Number *In Java* A rational number is one that can be expressed as the ratio of two integers, i.e., a number that can be expressed using a fraction whose numerator and denominator are integers. Examples of rational numbers are 1/2, 3/4 and 2/1. Rational numbers are thus no more than the fractions you've been familiar with since grade school. Rational numbers can be negated, inverted, added, subtracted, multiplied, and divided in the usual manner: The inverse, or reciprocal of...

  • Using Doubly Linked List, and Sorting methods: (In Java) (please attach your output with the answer)...

    Using Doubly Linked List, and Sorting methods: (In Java) (please attach your output with the answer) (Please answer if it is correct and working) (Have been getting many wrong and spam answers lately) Introduction: In this project, we use the same file structure of Artist and Art to extend the concepts of array and linked list and have them applied to sorting. The input files of p1arts.txt and p1artists.txt have been slightly modified. They are named p7arts.txt and p7artists.txt. Assignments:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT