问题
I have the following:
int num=Integer.parseInt(lineArray[0]);
byte numBit= num & 0xFF;
Is there any very simple way to convert numBit
to a bit array? Or even better, is there a way to bypass the byte conversion of the int and go straigh from num
to a bit array?
Thanks
回答1:
If you want a BitSet, try:
final byte b = ...;
final BitSet set = BitSet.valueOf(new byte[] { b });
If you want a 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;
}
or, equivalently,
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
};
}
回答2:
Java 7 has BitSet.valueOf(long[]) and BitSet.toLongArray()
int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
回答3:
You could do:
char[] bits = Integer.toBinaryString(num).toCharArray();
to get the underlying bit string as a char[]
E.g.
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;
}
You could create boolean []
array also this way.
回答4:
I came about this thread because Android added the BitSet.valueOf()
as late as in API 19.
I used oldrinb's 2nd snippet of the accepted answer but had to modify it because it had some errors. Additionally I modified it to return a BitSet, but it shouldn't be a problem to change it to boolean[]. See my comment to his reply.
This is the modification that now runs successfully:
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;
}
回答5:
Just an excercise in using streams (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));
}
来源:https://stackoverflow.com/questions/11820402/convert-a-byte-or-int-to-bitset