Is there anything I can cast a boolean array to in Java? It would be nice if I could say
boolean[] bools = new boolean[8];
int j = (int)bools;
But I'm not sure if that's feasible in Java.
Is there anything I can cast a boolean array to in Java? It would be nice if I could say
boolean[] bools = new boolean[8];
int j = (int)bools;
But I'm not sure if that's feasible in Java.
That syntax is not legal in Java.
What is it you are after? If you are looking for the length, you can do this:
int j = bools.length;
If you want a bit pattern, I think you're better off using bitmasks e.g.
final int BIT_1 = 0x00000001;
final int BIT_2 = 0x00000002;
// represents a bit mask
int value;
// enable bit 2
value |= BIT_2
// switch off bit 1
value &= ~BIT_1
// do something if bit 1 is set...
if (value & BIT_1) {
etc. See here for more examples.
the size of Java booleans is implementation specific, and it's probably not a single bit in any case. if you want an easy way to manipulate bits, take a look at BitSet.
Here's one quick-and-dirty way to convert from a boolean[]
to an integer:
static int intFromBooleanArray(boolean[] array) {
return new BigInteger(Arrays.toString(array)
.replace("true", "1")
.replace("false", "0")
.replaceAll("[^01]", ""), 2).intValue();
}
example:
intFromBooleanArray(new boolean[] {true, false, true, false, true, false});
// => 42.