tags:

views:

93

answers:

2

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  A: 
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

Chii
nice solution but I do not see how to do the reverse, the long size limitation might become a problem
stimpie
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...)
Chii
I have solved the size limitation by running the code for each 64bit block and concatinating the strings. thanks for your help
stimpie
if that is the case, it might be better just to perform a loop, and use BigDecimal (instead of doing bit shifting)
Chii
+2  A: 

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();
Kico Lobo
this works but uses a lot more space then a hexadecimal solution.
stimpie