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.
str[i].length()
is length of number say 2 in binary is 01 which is length 2 change 4 to desired max length of number. This can be optimized to O(n). by using continue.You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.
This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.
This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)
// Below will handle proper sizes
I think this is a suboptimal solution, but you could do