I have a short array {0,2,3,1,…} which I would like to convert to a BitSet.
Expected bits in bitset: 00 10 11 01 …
Every two bit in the bitset should represent a short. (2-bit precision) This should work fine for short values (0,1,2,3).
I know that I can use ByteBuffer and BitSet to access the bits of the numbers but those are formatted into 2 bytes (16 bit). I assume I need to bitshift the values to access the correct bits but I don't know how.
int nBit = 0;
BitSet result = new BitSet();
for (int i = 0; i < numbers.length; i ) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(number);
BitSet bits = BitSet.valueOf(buffer.array());
result.set(nBit , bits.get(?));
result.set(nBit , bits.get(?));
}
It there maybe an easier way?
CodePudding user response:
My current pragmatic solution which may be okay since only 4 values need to be handled:
public static BitSet transformToBitSet(short[] numbers) {
BitSet data = new BitSet();
int nBit = 0;
for (int i = 0; i < numbers.length; i ) {
short number = numbers[i];
switch (number) {
case 0:
data.set(nBit , false);
data.set(nBit , false);
break;
case 1:
data.set(nBit , true);
data.set(nBit , false);
break;
case 2:
data.set(nBit , false);
data.set(nBit , true);
break;
case 3:
data.set(nBit , true);
data.set(nBit , true);
break;
default:
throw new RuntimeException("Invalid number encountered. Can't map values >4");
}
}
return data;
}
CodePudding user response:
Here is one way to do it.
- set the desired bitLength (used for padding on the left with zero bits);
- initialize the BitSet index to 0.
- The iterate over the values.
- convert each to a bit string.
- pad on the left to achieve the desired bit length
- then set the bits based on the numeric value of the bit
BitSet b = new BitSet();
short[] vals = { 0, 2, 3, 1 };
int bitLength = 2;
int idx = 0;
for (short v : vals) {
String bits = Integer.toBinaryString(v);
bits = "0".repeat(bitLength - bits.length()) bits;
for (char c : bits.toCharArray()) {
b.set(idx , c - '0' == 1);
}
}
System.out.println(b)
prints
2,4,5,7
