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.
No, you can't do this with a boolean[] - but it sounds like you might want a BitSet which is a compact representation of a set of Boolean values.
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.
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.