I have:
public byte[] bytes = new byte[5]; //BitComp Class
public BitSet bits = new BitSet(40);
and the getters and setters in class named BitComp. The following class sets all the first 8 bits to 1(byte[0]).After that it converts all bytes to BitSet. Now after that when it sets the 2nd bit to true and prints both of them.
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();
}
}
Output:0000000000000000000000000000000011111111 <- 0th
0th-> 0100000000000000000000000000000011111111
There should not ne any change cause byte[0] contains the first 8 elements and I am setting the 2nd element as 1 with BitSet operation. So BitSet is approaching from LHS and Byte array is stored from RHS. How to approach this problem? Is there a problem in getBitsFromByte method? Please Suggest. Thanks