How to enter integer binary expression in bitSet in java

How to enter integer binary expression in bitSet in java?

say a = 15I want to put 1111in a bitSet,

is there a function for this?

+4
source share
2 answers

BitSethas a static method valueOf(long[])that

Returns a new bit containing all the bits in the specified long array.

So, an array with one long will have 64 bits, an array with two lengths will have 128 bits, etc.

If you need to get BitSetfrom only one value int, use it like this:

Integer value = 42;
System.out.println(Integer.toBinaryString(value));
BitSet bitSet = BitSet.valueOf(new long[] { value });
System.out.println(bitSet);

He is typing

101010
{1, 3, 5}

In other words, the 2nd, 4th, and 6th bits are set from right to left in the above representation.

+5

java ! =)

    int value = 10; //0b1010
    String bits = Integer.toBinaryString(value); //1010
    BitSet bs = new BitSet(bits.length());

=)

    for (int i = 0; i < bits.length(); i++) {
        if (bits.charAt(i) == '1') {
            bs.set(i);
        } else {
            bs.clear(i);
        }
    }
    System.out.println(bs); //{0, 2} so 0th index and 2nd index are set. 
+1

Source: https://habr.com/ru/post/1536890/


All Articles