Using padding, you can achieve something like the following. String.format("%0{n}d", number)
will not work here since the bitstring is not an integer and you can only prepend/append spaces to a string.
Output
0000001
0001000
1110001
0000100
Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
int[] values = { 1, 8, 113, 4 };
int width = -getMaxWidth(values);
for (int value : values) {
System.out.println(prettyPrintBitString(value, width));
}
}
public static String prettyPrintBitString(int value, int padding) {
return pad(Integer.toBinaryString(value), '0', padding);
}
public static int getMaxWidth(int[] values) {
return numberOfBits(Collections.max(toList(values)));
}
public static int numberOfBits(int value) {
return (int) (Math.floor(Math.log(value) / Math.log(2)) + 1);
}
public static List<Integer> toList(int[] values) {
List<Integer> list = new ArrayList<Integer>();
for (int value : values) list.add(value);
return list;
}
public static String pad(String str, char token, int count) {
StringBuilder padded = new StringBuilder(str);
if (count < 0) {
while (padded.length() < -count) padded.insert(0, token);
} else if (count > 0) {
while (padded.length() < count) padded.append(token);
}
return padded.toString();
}
}