将byte或int转换为bitset [英] Convert a byte or int to bitset
本文介绍了将byte或int转换为bitset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
int num=Integer.parseInt(lineArray[0]);
byte numBit= num & 0xFF;
有没有非常简单的方法来转换 numBit
有点阵?或者更好的是,有没有办法绕过int的字节转换并从 num
直接转到位数组?
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?
谢谢
推荐答案
如果你想要 BitSet ,试试:
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
};
}
这篇关于将byte或int转换为bitset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文