Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input an integer's binary expression into a bitSet in java

How to input an integer's binary expression into a bitSet in java?

say a = 15 I want put 1111 into a bitSet,

is there a function for this?

like image 511
user3495562 Avatar asked Mar 20 '23 20:03

user3495562


2 Answers

BitSet has a static valueOf(long[]) method which

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

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

If you only need to get a BitSet from a single int value, use it like so

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

It prints

101010
{1, 3, 5}

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

like image 199
Sotirios Delimanolis Avatar answered Mar 22 '23 11:03

Sotirios Delimanolis


In java you can do this! = )

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

Then add the result to the bitset = )

    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. 
like image 32
bezzoon Avatar answered Mar 22 '23 11:03

bezzoon