CSCI 210: Lab 2
Bitwise
Operations
Due:
11:59
PM
on
Monday,
June 21st
The Assignment
You can create your github repository by clicking here: https://classroom.github.com/a/25bLehqB. In the repository you will find a file named BitDriver.java with some testing code. You create a new file named BitOps.java that countains your code, and make sure that your code compiles and runs correctly with this test code.
In this assignment, you will write a java class named BitOps with seven different functions, described below. In this assignment, you will only use the java bit operators & (and), | (or),^ (xor), >> (right shift), >>> (right shift logical), and << (left shift). You will not receive credit for the assignment if you use addition, subtraction, division, multiplication, or mod/remainder. You will perform bit operations directly on the integer passed in on the command line, and you are not allowed to convert or change that integer in any way. For any function that asks you to change specific bits, you should assume bits are numbered 31 to 0, with 31 being the Most Significant Bit or highest bit, and 0 being the Least Signifcant Bit or lowest Bit. Most of these functions can be written in a single line of code.
For example, say I asked you to write a function named oneIsOne that sets bit one of an integer to one while leaving the rest of the bits unchanged. My code for that function would look like this:
public static int oneIsOne(int x){
return x | 2;
}
It may be helpful to know that you can specify the value of an
int in hex by prepending it with 0x, e.g. int x = 0xBADBEEF
. You
can also specify the value of an int in binary by prepending it with
0b, e.g. int x = 0b0110
.
You will need to write the following functions:
public static int isOdd(int x). This function returns 1 if the number is odd, and 0 if it is even. It returns 0 on 6, and 1 on 5.
public static int DivBy4(int x). This functions performs integer division by 4. It returns 1 on 6, 3 on 13, 0 on 3, and -4 on -16.
public static int nearestOdd(int x). This function rounds up the number to the nearest odd number. It returns 7 on 6, 5 on 5, and -3 on -4.
public static int flipParity(int x). This function adds 1 to even numbers, and subtracts one from odd numbers. It returns 7 on 6, 4 on 5, and -4 on -3.
public static int isNegative(int x). This function returns 0 if x is positive, and 1 if x is negative. It returns 0 on 4, and 1 on -3.
public static int clearBits(int x). This function sets all bits of x except bits 4 through 7 to 0. It leaves bits 4-7 unchanged. It returns 0 on 3, 128 on 128, 128 on 1668, and 240 on -3.
public static int setBits(int x). Set bits 4 through 7 of x to 0110. All other bits remain unchanged. It returns 99 on 3, 96 on 128, 1636 on 1668, and -147 on -3.
Handin
Make sure the final version of your code is pushed to your github repository.C. Taylor