Reputation: 31
int i = 10000;
Integer.toBinaryString(i);
How can I make the Integer.toBinaryString
method return leading zeroes as well? For example, for i = 1000
, I want 00000000000000000000001111101000
to appear, not 1111101000
.
Upvotes: 0
Views: 60
Reputation: 9416
If you want to left pad the result with zeros, you could do:
String raw = Integer.toBinaryString(i);
String padded = "0000000000000000".substring(raw.length()) + raw;
Here I chose a width of 16 digits, you can adjust the width by the number of zeros in the string.
Note, if it is possible that i > 2^16 - 1
then this will fail and you'll need to protect against that (32 zeros would be one approach).
Here's a more complicated version which formats to the smallest of 8, 16, 24, or 32 bits which will contain the result:
public class pad {
public static String pbi ( int i ) {
String raw = Integer.toBinaryString(i);
int n = raw.length();
String zeros;
switch ((n-1)/8) {
case 0: zeros = "00000000"; break;
case 1: zeros = "0000000000000000"; break;
case 2: zeros = "000000000000000000000000"; break;
case 3: zeros = "00000000000000000000000000000000"; break;
default: return raw;
}
return zeros.substring(n) + raw;
}
public static void main ( String[] args ) {
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer : ");
int i = s.nextInt();
System.out.println( pbi( i ) );
}
}
Upvotes: 1