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!!!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With