-1

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;
 }
}
sssuuuhg
  • 13
  • 1
  • You might want to take another look at what `Arrays.fill()` does: "Assigns the specified int value to **each element of the specified array** of ints." So, for each element in the list, you're filling the *entire array* with copies of that number. – azurefrog Jan 22 '20 at 23:04
  • 1
    Does this answer your question? [Convert list to array in Java](https://stackoverflow.com/questions/9572795/convert-list-to-array-in-java) – azurefrog Jan 22 '20 at 23:06
  • Just do it in a loop. No need for anything fancy. Or just work with the list directly. – WJS Jan 23 '20 at 00:37

1 Answers1

0

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.

WJS
  • 22,083
  • 3
  • 14
  • 32