Reputation: 387
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);
}
Upvotes: 0
Views: 1441
Reputation: 38531
You should use a BitSet
. If you want to do this yourself you can say:
public void set(int index) {
bits |= (1 << index);
}
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:
index
number of times.bits
equal to the value of bits
OR
'ed with the value from the previous stepUpvotes: 4