javalistloopsdecimalbinaries

I want to transform all the binaries in a Integer List to an decimal int


this is what I have atm:

I tried to convert the integers form the list to an int array. Problem is that the output is wrong. Logic is: last index from the array -> if 0 break else 2^index.

import java.util.Arrays;
import java.util.List;

public class BinaryArrayToNumber {

public static int ConvertBinaryArrayToInt(List<Integer> binary) {

    int x = 0;

    int[] binaries = new int[binary.size()];

    binary.forEach(integer -> {
        Arrays.fill(binaries, integer);
    });

    for (int j = binaries.length - 1; j>=0; j--) {
        if (binaries[j] == 0) break;
        else {
            x = (int) (x + Math.pow(2, j));
        }
    }
    return x;
 }
}

Solution

  • Okay, here is some help.

    First to copy from a list to an array, just do it in a loop.

        int[] binaries = new int[binary.size()];
        // here is how you copy the list.
    
        for (int i = 0; i < binary.size(); i++) {
             binaries[i] = binary.get(i);
        }
    

    Of course you can use the list without converting to an array.

    Now, for converting your list of bits into decimal value. You have the right idea but you need to think about where things are stored.

    Array indices        0  1  2  3
    And say the bits are 1, 1, 0, 1  with x = initialized to 0
    

    Using powers of 2 where ^ means exponentiation.

    x = binary[0] * 2^3 + x  // now x = 8
    x = binary[1] * 2^2 + x  // now x = 8 + 4 = 12
    x = binary[2] * 2^1 + x  // now x = 12 + 0 = 12
    x = binary[3] * 2^0 + x  // now x = 12 + 1 = 13.
    

    Now you just need to work with the for loop to obtain both the array index and the exponent as their values change inversely to each other.