Problem 9.2
Problem 9.2: Binary Numbers
In this problem, you will implement a class to encapsulate binary
numbers. Objects of your BinaryNumber class will be initialized from
a string of zeroes and ones. The BinaryNumber objects will be immutable,
i.e., no methods will change their data.
BinaryNumber objects will have methods to perform some simple calculations
and comparisons.
The specific requirements for the BinaryNumber class are:
-
Binary numbers are treated as unsigned values (so you don't need to
worry about two's complement arithmetic).
-
A BinaryNumber is constructed from a String of zeroes and ones.
-
A BinaryNumber can hold up to an eight bit unsigned value.
-
The BinaryNumber class must implement a method equals to compare
BinaryNumber objects for equality.
-
The BinaryNumber class must implement a method toString to produce
the string of eight zeroes and ones.
-
The BinaryNumber class must implement a method add to compute the
sum of BinaryNumber objects.
-
The BinaryNumber class must implement a method toInteger to produce
the decimal integer value of the binary number represented.
The testing code in the provided skeleton
gets two binary numbers on the command line or prompts for them,
and then performs some operations with them. You could adjust the driver
code to do some other arithmetic as well.
Here are some examples:
> java BinaryNumber 10011 101111
b1 is 00010011 (19)
b2 is 00101111 (47)
b1.equals(b2) is false
b3=b1.add(b2) is 01000010 (66)
b3=b3.add(b1) is 01010101 (85)
b2=b2.add(b1).add(b1) is 01010101 (85)
b2.equals(b3) is true
> java BinaryNumber 00000001 11111111
b1 is 00000001 (1)
b2 is 11111111 (255)
b1.equals(b2) is false
b3=b1.add(b2) is 00000000 (0)
b3=b3.add(b1) is 00000001 (1)
b2=b2.add(b1).add(b1) is 00000001 (1)
b2.equals(b3) is true
Constraints and Hints
-
Start with the skeleton code in BinaryNumber.java.
-
Your BinaryNumber implementation must use the array of boolean for
storing the binary number. In particular, you can not use an integer
variable for storing the binary representation.
-
Decide how you want to interpret the boolean array, i.e., does the first
the element of the array correspond to the most or least significant bit
in the number? Which ever way you choose to do this, you must be consistent
throughout the other methods so the arithmetic works.
-
Adding binary numbers must be performed using the array of booleans
rather than converting to an integer value.
Likewise, comparing binary numbers must also be performed using the
array of booleans rather than converting to integer or String values.
You can not use regular integer variables and arithmetic to
perform the binary addition.
-
When you add binary numbers, work from the least significant bit
and make sure to remember to carry. If the resulting value overflows
(i.e., is larger than eight bits allows) just drop the carry value.
The second example above shows this effect.
Turn-in
Turn in your BinaryNumber.java.