for example, for 1, 2, 128, 256
the output can be (16 digits):
0000000000000001
0000000000000010
0000000010000000
0000000100000000
I tried
String.format("%16s", Integer.toBinaryString(1));
it puts spaces for left-padding:
` 1'
How to put 0
s for padding. I couldn't find it in Formatter. Is there another way to do it?
Thanks in advance.
P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.
You can use Apache Commons StringUtils. It offers methods for padding strings:
Here a new answer for an old post.
To pad a binary value with leading zeros to a specific length, try this:
If
len = 4
andval = 1
,returns the string
"10001"
, thendiscards the very first character. So we obtain what we want:
If
val
is likely to be negative, rather try:I do not know "right" solution but I can suggest you a fast patch.
I have just tried it and saw that it works fine.