Classes/Objects  «Prev 


Java Bitwise Operators - Exercise

Objective:Use bitwise operators to store two short values in an int variable.

Scoring:

This exercise is worth 10 points.

Instructions

Write a class called Bitwise consisting of a single instance variable of type int and instance methods putLow(), putHigh(), getLow(), and getHigh().
The putLow() method should accept a parameter of type short and store this value in the low order 16 bits of the int instance variable. The putHigh() method should also accept a parameter of type short, but in this case, the value should be stored in the high order 16 bits of the int instance variable.
The getLow() and getHigh() methods should return the short values that were stored by the putLow() and putHigh() methods respectively.
To implement these instance methods it is recommended that you use the >>,<<, & and | operators. You will also need to use the (short) cast operator in your getLow() and getHigh() methods.
Here is a test application you can use to verify that your Bitwise class is working correctly:

class BitwiseTester { 
	public static void main(String[] args) {
    if (args.length != 2) {
		System.out.println("Usage: java BitwiseTester high low");
		System.exit(1);
	}
    short high = Short.parseShort(args[0]);
    short low  = Short.parseShort(args[1]);
    Bitwise b = new Bitwise();
    b.putHigh(high);
    b.putLow(low);
    high = b.getHigh();
    low  = b.getLow();
    System.out.println("high = " + high + ", low = " + low);
	}
}

Try running the above test application with several pairs of short values. Make sure you include negative numbers in your test.
In the text box below, cut and paste the source code for the Bitwise class. Click, Submit to submit the code.