javastringbinaryintegerbinary-string

How do I convert an array of integers to binary?


for (int i = 0; i < n; i++) {
    arr[i] = scanner.nextInt();
}
String[] bin = new String[n];
for (int i = 0; i < n; i++) {
    bin[i] = Integer.toBinaryString(arr[i]);
}

The above code will convert the the whole array of integers into an array of Strings (containing binary format of the input string), but there is a caveat.

For Example:
If the input array is: 2 3 7 10
The binary string array will be: 10
11
111
1010

But I want the output array to be like the following:
0010
0011
0111
1010

#2
If the input array is: 2 10 20
The binary string array will be:
10
1010
10100

But I want the output array to be like the following:
00010
01010
10100


Solution

  • To have all of the binary strings match the length of the longest String, you can first find the longest length and then use String#format and String#replace to pad with zeroes.

    int maxLen = 0;
    for (int i = 0; i < n; i++) {
        bin[i] = Integer.toBinaryString(arr[i]);
        maxLen = Math.max(maxLen, bin[i].length());
    }
    for (int i = 0; i < n; i++) {
        if (bin[i].length() != maxLen)
            bin[i] = String.format("%" + maxLen + "s", bin[i]).replace(' ', '0');
        System.out.println(bin[i]);
    }