Java – store the int value of the bitmask – extract the bit of 1 value
I'm calculating the int equivalent for the location set and storing it in memory From there, I want to determine all 1 value bits in the original bitmask Example:
33 – > [1,6] 97 – > [1,6,7]
The idea of implementing in Java?
Solution
On BitSet
Using Java util. BitSet to store a set of bits
Here is how to convert from int to BitSet according to which bit settings in 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)); // prints "{0,5}" System.out.println(fromInt(97)); // prints "{0,5,6}"
For completeness, here is the reverse transformation:
static int toInt(BitSet bs) { int num = 0; for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) { num |= (1 << k); } return num; }
Therefore, combining the two together, we always get the original number:
System.out.println(toInt(fromInt(33))); // prints "33" System.out.println(toInt(fromInt(97))); // prints "97"
0-based index
Note that this uses a 0 - based index, the more common bit index (and most other indexes in Java) This is also more correct Below, ^ denotes exponentiation:
33 = 2^0 + 2^5 = 1 + 32 97 = 2^0 + 2^5 + 2^6 = 1 + 32 + 64 33 -> {0,5} 97 -> {0,6}
However, if you insist on using a 1-based index, you can use BS set(k 1); (1 < (< (k-1)) in the above fragment However, I will strongly oppose this proposal Related questions > What does the ^ operator do in Java? – It's not actually exponentiation