Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 721
Rashid Raza Avatar asked Aug 15 '20 14:08

Rashid Raza


2 Answers

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]);
}
like image 107
Unmitigated Avatar answered Oct 13 '22 01:10

Unmitigated


You can first calculate the max binary string length of array then use Collections.nCopies to add extra 0 needed before string representation of binary string each.

int mx = 0;
for (int i = 0; i < n; i++) {
  bin[i] = Integer.toBinaryString(arr[i]);
  mx = Math.max(mx, bin[i].length());
}
for (int i = 0; i < n; i++) {
  bin[i] = String.join("", Collections.nCopies(mx - bin[i].length(), "0")) + bin[i];
}
like image 42
Eklavya Avatar answered Oct 13 '22 01:10

Eklavya