On BitSet
Use java.util.BitSetto save, well, a set of bits.
Here you can convert from intto BitSet, on the basis of which the bits are set to int:
static BitSet fromInt(int num) {
BitSet bs = new BitSet();
for (int k = 0; k < Integer.SIZE; k++) {
if (((num >> k) & 1) == 1) {
bs.set(k);
}
}
return bs;
}
So now you can do the following:
System.out.println(fromInt(33));
System.out.println(fromInt(97));
And just for completeness, here is the inverse transformation:
static int toInt(BitSet bs) {
int num = 0;
for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) {
num |= (1 << k);
}
return num;
}
So, making up together, we always return the original number:
System.out.println(toInt(fromInt(33)));
System.out.println(toInt(fromInt(97)));
When indexing based on 0
, 0, ( Java). . ^ :
33 = 2^0 + 2^5 = 1 + 32 97 = 2^0 + 2^5 + 2^6 = 1 + 32 + 64
33 -> {0, 5} 97 -> {0, 5, 6}
1, bs.set(k+1); (1 << (k-1)) . .