Integer.toBinaryString(data)
gives me a binary String representation of my array data.
However I would like a simple way to add leading ze
This is what you asked for—padding is added only when the value is zero.
String s = (data == 0) ? String.format("%0" + len + 'd', 0) : Integer.toBinaryString(data);
If what you really want is for all binary values to be padded so that they are the same length, I use something like this:
String pad = String.format("%0" + len + 'd', 0);
String s = Integer.toBinaryString(data);
s = pad.substring(s.length()) + s;
Using String.format()
directly would be the best, but it only supports decimal, hexadecimal, and octal, not binary.