Java,位向量

时间:2013-01-18 05:29:11

标签: java algorithm

我必须编写一个简单的方法,它接收索引并将该索引的“位”从0切换到1。我在为此编写按位运算符时遇到问题。我知道这很简单但我无法得到它。以下是该方法的样子。提前谢谢!

/** 
 * 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);
}

1 个答案:

答案 0 :(得分:4)

您应该使用BitSet。如果你想自己做,你可以说:

public void set(int index) { 
    bits |= (1 << index);
}

如果这是作业,上面的代码看起来很神奇,你真的需要阅读按位运算符。

此代码可以解释为:

  • 从数字1开始,将所有位移动index次。
  • bits的值设置为等于bits OR'ed的值,并使用上一步中的值