Array of Boolean for Integer

Asked

Viewed 346 times

2

How can I transform a Boolean array, boolean[] bits in his Integer correspondent?

I have a function that does exactly the opposite, but I didn’t understand it enough to be able to reverse it.

int input = 62;

boolean[] bits = new boolean[7];
for (int i = 6; i >= 0; i--) {
  bits[i] = (input & (1 << i)) != 0;
}

System.out.println(input + " = " + Arrays.toString(bits));
//saída: 62 = [false, true, true, true, true, true, false]

How can I get this array bits of example and have it as Integer returning the value 62 of input again?

  • I wavered in the answer. This gives not reading the question right.

  • I was commenting :x ahaha, I even edited the question, I may have expressed myself badly

1 answer

2


Making another one for, try this way:

int n = 0, l = bits.length;
for (int i = 0; i < l; ++i) {
    n = (n << 1) + (bits[i] ? 1 : 0);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.