簡體   English   中英

Java,位向量

[英]Java, bit vectors

我必須編寫一個簡單的方法,該方法接受一個索引並將該索引處的“位”從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);
}

您應該使用BitSet 如果您想自己做,可以說:

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

如果這是家庭作業,並且上面的代碼看起來像魔術,那么您確實需要閱讀按位運算符。

此代碼可以解釋為:

  • 從數字1開始,然后將其所有位移動index次數。
  • bits的值設置為等於bits的值OR與上一步中的值bits

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM