1

I want to convert binary List to binary int[]. My code is as is below:

public class BinListToIntArr {
    public static void main(String[] args) {
        List<String[]> arrList = new ArrayList<>();

        //fill it
        arrList.add(new String[] {"0011","1100","1111","1111","0000"});
        arrList.add(new String[] {"0101","1111","1010","0000","0101"});
        arrList.add(new String[] {"1111","1010","0000","0101","1111"});
        arrList.add(new String[] {"1010","0000","1111","0101","1100"});
        arrList.add(new String[] {"0000","1110","1100","0001","0011"});

        //convert it
        ArrayList<Integer> ints = new ArrayList<>();
        for (String[] array : arrList) {
            for (String str : array) {
                ints.add(Integer.parseInt(str));
            }
        }

        Integer[] result = ints.toArray(new Integer[] {});

        for (int i : result){
            System.out.println(i);
        }
    }
}

The result supposed to be:

0011
1100
1111
1111
0000
1010
1111
1010
0000
1010
1111
1010
0000
1010
1111
1010
0000
1111
1010
1100
0000
1110
1100
1000
1100

But I got this result:

11
1100
1111
1111
0
101
1111
1010
0
101
1111
1010
0
101
1111
1010
0
1111
101
1100
0
1110
1100
1
11

In which part I made a mistake? Is there anybody can help? Because no matter I tried, 0 in String always disappear when I convert it into int. Is it possible to make 0 in String not disappear when we convert to int? If yes, how?

0

1 Answer 1

1

Don't confuse an int and a String representation of an int since an int is just a number and will never be able to understand or store something like leading 0's. If you want to display leading 0's then format your output. String.format(...) or System.out.printf(...) would work, for example:

  for (int i : result) {
     System.out.printf("%04d%n", i);
  }

Which outputs:

0011
1100
1111
1111
0000
0101
1111
1010
0000
0101
1111
1010
0000
0101
1111
1010
0000
1111
0101
1100
0000
1110
1100
0001
0011

The "%04d" format specifier says print a String from an int that is four chars wide and that has leading 0's.

Edit: I forgot to add the %n within the format String since you wish to print a new line as well. This has now been added.

Sign up to request clarification or add additional context in comments.

3 Comments

It's working to print! So, the value itself doesn't change, right? I mean, the result both in List<String[]> is same with int[] result, am I correct?
@user3698011: the values are totally different. One hold Strings and one holds ints, two completely different types that hold different information.
Thank you for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.