Boolean Array for Integer

2

How can I transform a boolean array, boolean[] bits into its corresponding Integer ?

I have a function that does exactly the opposite, but I did not understand it enough to be able to invert 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 do to get this array bits of the example and have it as Integer returning the value 62 of the input again?

    
asked by anonymous 31.08.2017 / 21:13

1 answer

2

Doing another for, try this:

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