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.
A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":
I was trying all sorts of method calls that I haven't really used before to make this work, they worked with moderate success, until I thought of something that is so simple it just might work, and it did!
I'm sure it's been thought of before, not sure if it's any good for long string of binary codes but it works fine for 16Bit strings. Hope it helps!! (Note second piece of code is improved)
Thanks to Will on helping improve this answer to make it work with out a loop. This maybe a little clumsy but it works, please improve and comment back if you can....
I would write my own util class with the method like below
}
Output:
The same approach could be applied to any integral types. Pay attention to the type of mask
long mask = 1L << i;
There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:
Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so. Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:
A naive solution that work would be
One other method would be
This will produce a 16 bit string of the integer 5
try...
I dont think this is the "correct" way to doing this... but it works :)