3

Howto convert a boolean array (or BitSet) to a string and vice versa.

Example:

boolean[] ar = {true,false,false,false,false};
print(BitArrayToString(ar));

Should return one of the following

10000 //binary
16 //decimal
10 //hex, prefered

The otherway around should work also

ar = StringToBitArray(BitArrayToString(ar));

2 Answers 2

3
long bitSetInt = 0;
for (int i = 0 ; i < ar.length ; i++) {
   bitSetInt = (bitSetInt | toDigit(ar[i])) << 1;
}
println(String.format("%x", bitSetInt));

where

int toDigit(boolean b) { return b?1:0;}

works as long as the ar array is less then the size of a long. Use http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax for other formatting needs

Sign up to request clarification or add additional context in comments.

4 Comments

nice solution but I do not see how to do the reverse, the long size limitation might become a problem
because this smelt like homework, i didnt provide the full solution - just half. have a little think - its very easy to convert a digit into an array of bools.(and yes, the size limit of a long is indeed a problem, but the question didnt spec the max size...)
I have solved the size limitation by running the code for each 64bit block and concatinating the strings. thanks for your help
if that is the case, it might be better just to perform a loop, and use BigDecimal (instead of doing bit shifting)
2

Well, you could do something like this:

StringBuilder builder = new StringBuilder();
for (int i = 0; i < array.length; i++) {
    if (array[i]) builder.append("1"); else builder.append("0");
}
return builder.toString();

1 Comment

this works but uses a lot more space then a hexadecimal solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.