Try,
String output= String.format("%"+numberOfZerosToPut+"s",
Integer.toBinaryString(3)).replace(' ', '0');
System.out.println(output);
Question
I know about Integer.toBinaryString(int i)
, but what I am trying to decide how to do is append a certain number of bits (0's)
to the end of it as needed.
Example: I have the integer 3
which is represented by 11 in binary
, but I want it to be 7 digits (bits) long in total so it will get the length of the binary value (in this case 2 bits) and then add 5 0's to the start so you will finish with 0000011
for a total of 7 bits
.
Solution
Try,
String output= String.format("%"+numberOfZerosToPut+"s",
Integer.toBinaryString(3)).replace(' ', '0');
System.out.println(output);
OTHER TIPS
Create a method like this :
public static String appendZeroes(String bits) {
int rem = bits.length()%8;
if(rem == 0)
return bits;
else
{
int appendingZeroes = 8-rem;
String s = "";
for(int i=0;i<appendingZeroes;i++)
s+="0";
s=s+bits;
return s;
}
}