I have to write a simple method that takes in an index and switches the “bit” at that index from 0 to 1. I am having trouble writing the bitwise operators for this. I know it is simple but I can not get it. Below is what the method looks like. Thank you in advance!
/**
* 32-bit data initialized to all zeros. Here is what you will be using to represent
* the Bit Vector.
*/
private int bits;
/** You may not add any more fields to this class other than the given one. */
/**
* Sets the bit (sets to 1) pointed to by index.
* @param index index of which bit to set.
* 0 for the least significant bit (right most bit).
* 31 for the most significant bit.
*/
public void set(int index)
{
//It is here where I can not figure it out. Thank you!
System.out.println(~bits);
System.out.println("setting bit: " + bits + " to: " + index);
}
You should use a
BitSet. If you want to do this yourself you can say:If this is homework, and the above code looks like magic, you really need to read up on bitwise operators.
This code can be interpreted as:
indexnumber of times.bitsequal to the value ofbitsOR‘ed with the value from the previous step