Question

Define a class BinaryNumber that represents binary numbers and a few simple operations on them, as...

Define a class BinaryNumber that represents binary numbers and a few simple operations on them, as indicated below.

An example of a binary number is 1011 Its length is 4. Note that its leftmost digit is the least significant one: it represents the decimal number 1∗20 +0∗21 +1∗22 +1∗23 = 13. This is called little-endian format. You may use big-endian if you prefer; in that case you must state so at the beginning of your code as part of the comment. This assignment requests that a number of operations be supported. They are divided into two groups.

The first is a set of basic operations, the second is slightly more challenging and addresses addition of binary numbers.

2.1 Basic operations The following operations should be supported:

• A constructor BinaryNumber(int length) for creating a binary number of length length and consisting only of zeros.

• A constructor BinaryNumber(String str) for creating a binary number given a string. For example, given the string "1011", the corresponding binary number should be created. For this exercise you will have to use some standard String operations. These are listed in the “Hints” section below.

• An operation int getLength() for determining the length of a binary number. • An operation int getDigit(int index) for obtaining a digit of a binary number given an index. The starting index is 0. If the index is out of bounds, then a message should be printed on the screen indicating this fact.

• An operation int toDecimal() for transforming a binary number to its decimal notation (cf. the example given above).

• An operation void shiftR(int amount) for shifting all digits in a binary number any number of places to the right, as indicated by a parameter amountToShift. The new digit should be 0. For example, the result of shifting “1011” 3 places to the right should yield “0001011”.

2.2 Addition of Binary Numbers Here is an example of how two binary numbers of the same length are added1. 1 1 1 1 (carried digits) 10110 +11100 = 0 0 1 0 1 =20 Note that it is possible for the addition of two numbers to yield a result which has a larger length than the summands. In that case, this should be flagged by an appropriate boolean data field. Here is such an example. 1 1 1 1 1 (carried digits) 10110 +11101 = 0 0 1 0 0 1 =36 This data field should be added to the data fields of the class BinaryNumber. Implement the following operations:

• void add(BinaryNumber aBinaryNumber) for adding two binary numbers, one is the binary number that receives the message and the other is given as a parameter. If the lengths of the binary numbers do not coincide, then a message should be printed on the screen indicating this fact. Otherwise, it modifies the receiving binary number with the result of the addition.

• An operation clearOverflow() that clears the overflow flag. • An operation String toString() for transforming a binary number to a String. If the number is the result of an overflow, the string “Overflow” should be returned.

2.3

Hints 3 •

• For the BinaryNumber(String str) constructor, the following operations might come in handy:

– char java.lang.String.charAt(int index), which returns the char value at the spec- ified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

– int java.lang.Character.getNumericValue(char ch), which returns the int value that the specified Unicode character represents.

For the shiftR(int amount) operation, it might be useful to define an auxiliary private method reallocate, that makes room for a new digit. This operation would in turn use int[] java.util.Arrays.copyOf(int[] original, int newLength), which copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

The code must implement the following UML diagram precisely

BinaryNumber

private int data[]

private boolean overflow

public BinaryNumber(int length)

public BinaryNumber(String str)

public int getLength()

public int getDigit(int index)

public void shiftR(int amount)

public void add(BinaryNumber aBinaryNumber)

public String toString()

public int toDecimal()

public void clearOverflow()

Homework Answers

Answer #1
import java.util.Arrays;

public class BinaryNumber {

    private int digits[];
    private boolean overFlow = false;

    public BinaryNumber(int n) {
        digits = new int[n];
    }

    public BinaryNumber(String r) {
        digits = new int[r.length()];
        
        for(int i=0; i<r.length(); i++) {
            digits[i] = r.charAt(i) - '0';
        }
    }

    public int getLength() {
        return digits.length;
    }

    public int toDecimal() {
        int w = 1;
        int value = 0;

        for (int c : digits) {
            value += c * w;
            w *= 2;
        }
        return value;
    }

    public int getDigit(int index) {
        return digits[index];
    }

    void shiftR(int amount) {
        
        int temp[] = Arrays.copyOf(digits, digits.length + amount);
        
        for(int i=temp.length-1; i>=amount; i--) {
            temp[i] = digits[i-amount];
        }
        for(int i=0; i<amount; i++) {
            temp[i] = 0;
        }
        
        digits = temp;
    }

    void add(BinaryNumber aBinaryNumber) {
        if (getLength() != aBinaryNumber.getLength()) {
            System.out.println("Lengths of numbers to be added is not same.");
        } else {
            int carry = 0;

            for (int i = 0; i < digits.length; i++) {
                int s = carry + getDigit(i) + aBinaryNumber.getDigit(i);

                if (s >= 10) {
                    s = s - 10;
                    carry = 1;
                } else {
                    carry = 0;
                }

                digits[i] = s;
            }

            if (carry != 0) {
                overFlow = true;
            }
        }
    }

    public void clearOverflow() {
        overFlow = false;
    }

    @Override
    public String toString() {
        if (overFlow) {
            return "Overflow";
        }
        String s = "";
        for(int x: digits) {
            s += x;
        }
        return s;
    }
}

**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Know the answer?
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
Similar Questions
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
USE C programming (pls label which file is libcipher.h and libcipher.c) Q4) A shift cipher is...
USE C programming (pls label which file is libcipher.h and libcipher.c) Q4) A shift cipher is one of the simplest encryption techniques in the field of cryptography. It is a cipher in which each letter in a plain text message is replaced by a letter some fixed number of positions up the alphabet (i.e., by right shifting the alphabetic characters in the plain text message). For example, with a right shift of 2, ’A’ is replaced by ’C’, ’B’ is...
Objectives:The focus of this assignment is to create and use a recursive method given a moderately...
Objectives:The focus of this assignment is to create and use a recursive method given a moderately difficult problem. Program Description: This project will alter the EmployeeManager to add a search feature, allowing the user to find an Employee by a substring of their name. This will be done by implementing the Rabin-Karp algorithm. A total of seven classes are required. Employee (From previous assignment) HourlyEmployee (From previous assignment) SalaryEmployee (From previous assignment) CommissionEmployee (From previous assignment) EmployeeManager (Altered from previous...
Implement and demonstrate a disk-based buffer pool class based on the LRU buffer pool replacement strategy....
Implement and demonstrate a disk-based buffer pool class based on the LRU buffer pool replacement strategy. Disk blocks are numbered consecutively from the beginning of the file with the first block numbered as 0. Assume that blocks are 4096 bytes in size. Use the supplied C++ files to implement your LRU Buffer Pool based on the instructions below. • Implement a BufferBlock class using the supplied BufferBlockADT.h o Your Buffer Block must inherit BufferBlockADT or you will not get credit...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 565 Error 2 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 761 I need this code to COMPILE and RUN, but I cannot get rid of this error. Please Help!! #include #include #include #include using namespace std; enum contactGroupType {// used in extPersonType FAMILY, FRIEND, BUSINESS, UNFILLED }; class addressType { private:...
is there anything wrong with the solution. the question are from java course Write a main...
is there anything wrong with the solution. the question are from java course Write a main method that will request the user to enter Strings using a JOptionPane input dialog. The method should continue accepting strings until the user types “STOP”.       Then, using a JOptionPane message dialog, tell the user how many of the strings begin and end with a digit. Answer: import javax.swing.*; public class IsAllLetters {     public static void main(String[] args) {         String input;         int count =...
Write a Java program named BinaryConversion that will convert base 2 numbers to base 10 numbers....
Write a Java program named BinaryConversion that will convert base 2 numbers to base 10 numbers. The data for this program will be entered from the keyboard using JOptionPane one 16-bit binary number at a time. Note that each base 2 number is actually read in as a String. The program should continue until a 16-bit base 2 number consisting of all 0’s is entered. Once the 16-bit number has been entered your program should make sure that the input...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative sort that sorts the vehicle rentals by color in ascending order (smallest to largest) Create a method to binary search for a vehicle based on a color, that should return the index where the vehicle was found or -1 You are comparing Strings in an object not integers. Ex. If the input is: brown red white blue black -1 the output is: Enter the...
Step 1: Edit StringExplode.java Download the StringExplode.java file, and open it in jGrasp (or a text...
Step 1: Edit StringExplode.java Download the StringExplode.java file, and open it in jGrasp (or a text editor of your choice). This program will “explode” a String into an array of characters (char[]), and then print out the array. The String comes from the first command-line argument. Example output with the command-line argument foo is below: f o o --------------------------------------------------------------------- public class StringExplode { // TODO - write your code below this comment. // You will need to write a method...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String...
please fix code to delete by studentname import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public void addStudent(String student) {         if (numberOfStudents == students.length) {             String[] a = new String[students.length + 1];            ...