开发者

Convert boolean[] to String and viceversa in java

开发者 https://www.devze.com 2022-12-14 10:59 出处:网络
Howto convert a boolean array (or BitSet) to a string and vice versa. Example: boolean[] ar = {true,false,false,false,false};

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 开发者_如何学JAVAotherway around should work also

ar = StringToBitArray(BitArrayToString(ar));


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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消