1

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.

3
  • Do want to treat the boolean array as a bit pattern and convert to the int value of the pattern? Commented Oct 6, 2009 at 21:31
  • Are you trying to get the pointer to the boolean array? Commented Oct 6, 2009 at 21:36
  • 2
    What's your expectation of how an array of booleans is mapped to an integer? Commented Oct 6, 2009 at 21:47

5 Answers 5

4

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.

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

Comments

3

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.

1 Comment

They are not only implementation specific, but almost always full "int" size (or, more accurately, machine word size). To not do it this way would slow down your system.
3

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.

Comments

3

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.

1 Comment

Could you add more detail on the etc part?
0

You can cast boolean[] to Object, but that's about it.

Comments

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.