Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!

like image 475
Jevin129 Avatar asked Oct 28 '15 05:10

Jevin129


1 Answers

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;
}
like image 60
Stanislav Avatar answered Sep 22 '22 14:09

Stanislav