[英]Convert a byte or int to bitset
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? 有没有非常简单的方法将
numBit
转换为位数组? Or even better, is there a way to bypass the byte conversion of the int and go straigh from num
to a bit array? 或者更好的是,有没有办法绕过int的字节转换并从
num
直到数组?
Thanks 谢谢
If you want a BitSet , try: 如果你想要一个BitSet ,试试:
final byte b = ...;
final BitSet set = BitSet.valueOf(new byte[] { b });
If you want a boolean[]
, 如果你想要一个
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
};
}
Java 7 has BitSet.valueOf(long[]) and BitSet.toLongArray() Java 7有BitSet.valueOf(long [])和BitSet.toLongArray()
int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
You could do: 你可以这样做:
char[] bits = Integer.toBinaryString(num).toCharArray();
to get the underlying bit string as a char[]
将基础位字符串作为
char[]
Eg 例如
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. 你也可以用这种方式创建
boolean []
数组。
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. 我来到这个线程是因为Android在API 19中添加了
BitSet.valueOf()
。我使用了oldrinb的第二段接受的答案,但由于它有一些错误而不得不修改它。 Additionally I modified it to return a BitSet, but it shouldn't be a problem to change it to boolean[]. 另外我修改它以返回一个BitSet,但将它更改为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;
}
Just an excercise in using streams (J8+): 只是一个使用流的练习(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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.