Jevin129
Jevin129

Reputation: 81

Large String of 1 and 0 to BitSet

I have a very large string ( 64 characters) containing 1s and 0s. sample - 1001111111101010011101101011100101001010111000101111011110001000

All I want is to convert it into BitSet var containing the 1s and 0s in same positions I am using the function -

private static BitSet fromString(String binary) {
        return BitSet.valueOf(new long[] { Long.parseLong(binary, 2) });
}

and have already gone through - Java BitSet Example I have actually figured out the issue and that is my 64th bit being 1 and the function throwing up a number format exception I have tried plethora of other conversions but can't get it working Any help here would be appreciated Thanks!!!

Upvotes: 7

Views: 6335

Answers (2)

Michail Alexakis
Michail Alexakis

Reputation: 1585

A solution using Stream API:

final String s = "1001..." // the input string
final int n = s.length();
BitSet set = IntStream.range(0, n)
   .filter(i -> s.charAt(i) == '1')
   .collect(() -> new BitSet(n), (t, i) -> t.set(i) , (t1, t2) -> t1.or(t2));

Upvotes: 0

Stanislav
Stanislav

Reputation: 28106

Since you have a string, contatining 0s and 1s only, you can simply do it without casting to Long, just using String#charAt() and BitSet#set(). For example, like so:

private static BitSet fromString(String binary) {
    BitSet bitset = new BitSet(binary.length());
    for (int i = 0; i < binary.length(); i++) {
        if (binary.charAt(i) == '1') {
            bitset.set(i);
        }
    }
    return bitset;
}

Or with r-l orientation, as it usually used:

private static BitSet fromString(String binary) {
    BitSet bitset = new BitSet(binary.length());
    int len = binary.length();
    for (int i = len-1; i >= 0; i--) {
        if (binary.charAt(i) == '1') {
            bitset.set(len-i-1);
        }
    }
    return bitset;
}

Upvotes: 8

Related Questions