我有:
public byte[] bytes = new byte[5]; //BitComp Class
public BitSet bits = new BitSet(40);
以及名为 BitComp 的类中的 getter 和 setter。以下类将所有前 8 位设置为 1(byte[0])。之后,它将所有字节转换为 BitSet。现在,当它将第二位设置为 true 并打印它们时。
import java.util.BitSet;
public class TestBitSet {
public void testBit(){
BitComp comp = new BitComp();
comp.bytes[0] |= 0xFF;
comp.setBits(getBitsFromByte(comp.getBytes()));
System.out.println(toCharArray(comp.getBits()));
BitSet bs = comp.getBits();
bs.set(1,true);
comp.setBits(bs);
System.out.println(toCharArray(comp.getBits()));
}
private BitSet getBitsFromByte(byte[] barray)
{
BitSet bits=new BitSet();
if(barray!=null)
{
for (int i=0; i<barray.length*8; i++)
{
if ((barray[barray.length-i/8-1]&(1<<(i%8)))!= 0)
{
bits.set(i);
}
}
}
return bits;
}
public static char[] toCharArray(final BitSet bs)
{
final int length = bs.length();
final char[] arr = new char[length];
for(int i = 0; i < length; i++)
{
arr[i] = bs.get(i) ? '1' : '0';
}
return arr;
}
public static void main(String args[]){
TestBitSet tbs = new TestBitSet();
tbs.testBit();
}
}
输出:00000000000000000000000000000000011111111 <- 0th
0th-> 0100000000000000000000000000000011111111
不应该有任何变化,因为 byte[0] 包含前 8 个元素,我使用 BitSet 操作将第二个元素设置为 1。所以 BitSet 是从 LHS 接近的,而 Byte 数组是从 RHS 存储的。如何解决这个问题?getBitsFromByte 方法有问题吗?请建议。谢谢