Search code examples
javaapibitset

what is the purpose of BitSet valueOf in fromString method


I would appreciate an explanation of what this line does exactly.

BitSet.valueOf(new long[] { Long.parseLong(s, 2) });

While this code example posted by FauxFaus really helped me understand BitSet usage, I don't find the purpose of the above line or why. here is the full example:

package com.tutorialspoint;
import java.util.*;
import java.util.BitSet;
public class TimeZoneDemo {
public static void main(String[] args) {
    BitSet bits1 = fromString("1000001");
    BitSet bits2 = fromString("1111111");
    System.out.println(toString(bits1)); // prints 1000001
    System.out.println(toString(bits2)); // prints 1111111

    bits2.and(bits1);

    System.out.println(toString(bits2)); // prints 1000001
}

private static BitSet fromString(final String s) {
    System.out.println(BitSet.valueOf(new long[] { Long.parseLong(s, 2) }));
    return BitSet.valueOf(new long[] { Long.parseLong(s, 2) });
}
private static String toString(BitSet bs) {
    return Long.toString(bs.toLongArray()[0], 2);
}
}

Please note that I can't comment on the original answer to ask the OP.


Solution

  • Long.parseLong(s, 2) parses the String s as a binary String. The resulting long is put in a long array and passed to BitSet.valueOf to generate a BitSet whose bits represent the bits of that long value.

    The reason BitSet.valueOf takes long array instead of a single long is to allow creation of BitSets having more than 64 bits.