我正在计算一组钻头的int等效,并将其存储在内存中。从那里,我想从原始位掩蔽中确定所有1个值位。例子:

33 --> [1,6]
97 --> [1,6,7]

在Java实施的想法?

有帮助吗?

解决方案

BitSet

利用 java.util.BitSet 存放一组碎片。

这是您可以从一个转换的方式 intBitSet, ,基于哪个位 int 设置:

static BitSet fromInt(int num) {
    BitSet bs = new BitSet();
    for (int k = 0; k < Integer.SIZE; k++) {
        if (((num >> k) & 1) == 1) {
            bs.set(k);
        }
    }
    return bs;
}

因此,现在您可以执行以下操作:

System.out.println(fromInt(33)); // prints "{0, 5}"
System.out.println(fromInt(97)); // prints "{0, 5, 6}"

只是为了完整性,这是反向转换:

static int toInt(BitSet bs) {
    int num = 0;
    for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) {
        num |= (1 << k);
    }
    return num;
}

因此,将两者兼而有之,我们始终恢复原始数字:

System.out.println(toInt(fromInt(33))); // prints "33"
System.out.println(toInt(fromInt(97))); // prints "97"

在0基索引上

请注意,这是基于0的索引,这是位的更常用的索引(以及Java中的大多数所有内容)。这也更正确。在下面的, ^ 表示指数:

33 = 2^0 + 2^5 = 1 + 32          97 = 2^0 + 2^5 + 2^6 = 1 + 32 + 64
33 -> {0, 5}                     97 -> {0, 5, 6}

但是,如果您坚持使用1个基于1个索引,则可以使用 bs.set(k+1);(1 << (k-1)) 在上面的片段中。但是,我强烈建议您提出这一建议。

相关问题

其他提示

对于BIT PRIDDLING,Java.lang.integer具有一些非常有用的静态方法。尝试此代码作为您问题的起始基础:

public int[] extractBitNumbers(int value) {
    // determine how many ones are in value
    int bitCount = Integer.bitCount(value);
    // allocate storage
    int[] oneBits = new int[bitCount];
    int putIndex = 0;
    // loop until no more bits are set
    while (value != 0) {
        // find the number of the lowest set bit
        int bitNo = Integer.numberOfTrailingZeros(value);
        // store the bit number in array
        oneBits[putIndex++] = bitNo+1; 
        // clear the bit we just processed from the value
        value &= ~(1 << bitNo);      
    }
    return oneBits;
}

我可以向您展示C#实现,Java应该非常相似。

int value = 33;
int index = 1;

while (value > 0)
{
   if ((value % 2) == 1)
      Console.WriteLine(index);

   index++;
   value /= 2;
}

如果您想获得这样的数组 & 每个步骤的整数有点移动1。

像(伪)这样的东西:

Init array
mask = 1
for (0 to BitCount):
  if Integer & mask
    array[] = pos
  mask << 1

轻微的变化将是类似的:

int[] getBits(int value) {
  int bitValue = 1;
  int index = 1;
  int[] bits = new int[33];

  while (value >= bitValue)
  {
    bits[index++] = (value & bitValue);
    bitValue << 1; // or: bitValue *= 2;
  }
  return bits;
}

请注意,由于按照您的要求从1索引,因此 bits[0] 没有使用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top