views:

74

answers:

2

Hey,

A boolean array can be considered to be a binary number e.g.

boolean[] four = {true, false, false}; //100

I would like to convert such an array to its decimal equivalent e.g.

int decimal = convertBooleanArrayToDecimal(four);
//decimal == 4

How can I do so?

Cheers,

Pete

+5  A: 

Try something like this.

long result = 0;
for (boolean bit : four) {
    result = result * 2 + (bit ? 1 : 0);
}
Nikita Rybak
Please review that expression! I believe you're multiplying by (2 + bit) rather than adding bit and multiplying by 2.
Carl Smotricz
@Carl: I'm pretty sure the multiplication takes precedence. But a pair of parens to clarify/ensure it wouldn't hurt.
BlairHippo
@Carl You're right, I saw mistake too and fixed it.
Nikita Rybak
@BlairHippo there was a mistake initially, but I corrected it in few seconds.
Nikita Rybak
@Nikita: Heh. Whoops. Just ignore me, I always do....
BlairHippo
+2  A: 

An alternate solution:

long result = 0;
for (boolean bit: boolArray)
{
    result <<= 1;
    if (bit) result += 1;
}

This is mathematically equivalent to Nikita's solution, but I find the bit-shifting version to be clearer.

JSBangs