简体   繁体   中英

Java, bit vectors

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:

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:

  • Start with the number 1, and move all of its bits over index number of times.
  • Set the value of bits equal to the value of bits OR 'ed with the value from the previous step

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM