将一个字节或整数转换为位集合。

15

我有以下代码:

int num=Integer.parseInt(lineArray[0]);
byte numBit= num & 0xFF;

有没有非常简单的方法将numBit转换为位数组?或者更好的是,是否有一种方法可以绕过int的字节转换并直接从num转换成位数组?

谢谢


2
我猜这对你的情况也适用... [Stackoverflow - Bitset to and from Integer Long] - Pr0gr4mm3r
1
你是指 boolean[] 还是 BitSet - dacwe
5个回答

15
如果你需要一个BitSet,请尝试使用以下方法:valueOf(byte[])
final byte b = ...;
final BitSet set = BitSet.valueOf(new byte[] { b });

如果你需要一个boolean[]

static boolean[] bits(byte b) {
  int n = 8;
  final boolean[] set = new boolean[n];
  while (--n >= 0) {
    set[n] = (b & 0x80) != 0;
    b <<= 1;
  }
  return set;
}

或者等价地说,

static boolean[] bits(final byte b) {
  return new boolean[] {
    (b &    1) != 0,
    (b &    2) != 0,
    (b &    4) != 0,
    (b &    8) != 0,
    (b & 0x10) != 0,
    (b & 0x20) != 0,
    (b & 0x40) != 0,
    (b & 0x80) != 0
  };
}

我看到了这个答案,想指出BitSet.valueOf()方法只在Java 7及以上版本中才有。虽然问题没有指定Java版本,但如果你使用的是Java 6,你应该能够采用其中一种方法创建一个boolean[]来填充一个BitSet对象。 - Thomas Owens
1
你的第二个片段中应该是 set[n] = (b & 0x80) != 0;,而且你需要在 while 循环中进行后置递增:while (n-- > 0)。否则你会跳过第 0 位比特。 - Jaykob

5
Java 7有BitSet.valueOf(long[])和BitSet.toLongArray()。
int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});

1
你可以使用以下代码:

char[] bits = Integer.toBinaryString(num).toCharArray();

来获取底层的位串作为char[]

例如:
public BitSet getBitSet(int num){
    char[] bits = Integer.toBinaryString(num).toCharArray();  
    BitSet bitSet = new BitSet(bits.length);  
    for(int i = 0; i < bits.length; i++){  
        if(bits[i] == '1'){
            bitSet.set(i, true);
        }
        else{
            bitSet.set(i, false);
        }                
    }
    return bitSet;
}  

您可以通过以下方式创建boolean []数组。

1
你在这里做了重复的工作-- toBinaryString() 也会迭代位。你最好使用循环,同时 i < Integer.SIZE 和直接位测试 0 < (num & 1 << i)。更不用说新的 BitSet 中的位已经预设为 false。简单来说,你的代码既冗长又低效。 - charlie

0

我看到这个帖子是因为Android在API 19中才添加了BitSet.valueOf()。 我使用了oldrinb的第二个代码片段,但不得不修改它,因为它有一些错误。此外,我将其修改为返回一个BitSet,但将其更改为boolean[]应该不是问题。请参见我的回复评论。

这是现在成功运行的修改:

public static BitSet toBitSet(byte b) {
    int n = 8;
    final BitSet set = new BitSet(n);
    while (n-- > 0) {
        boolean isSet = (b & 0x80) != 0;
        set.set(n, isSet);
        b <<= 1;
    }
    return set;
}

0

这只是一个使用(J8+)的练习:

// J7+
BitSet bitSet(final long... nums) {
    return BitSet.valueOf(nums);
}

// J8+
final IntStream bitsSet = bitSet(num).stream();

// vice-versa
BitSet bitSet(final IntStream bitsSet) {
    return bitsSet.collect(BitSet::new, BitSet::set, BitSet::or);
}

// without BitSet
IntStream bitsSet(final long... nums) {
    return IntStream.range(0, nums.length)
            .flatMap(n -> IntStream.range(0, Long.SIZE - 1)
                    .filter(i -> 0 != (nums[n] & 1L << i))
                    .map(i -> i + n * Long.SIZE));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接