这是一个古老的技巧,创建一个带有16 0的字符串,然后附加从String.format(“%s”,Integer.toBinaryString(1))中获得的修剪后的二进制字符串,并使用最右边的16个字符,从而忽略所有前导0。更好的是,创建一个函数,让您指定所需的二进制字符串长度。当然,可能还有数不胜数的其他方法可以做到这一点,包括库,但是我要添加这篇文章来帮助一位朋友:)
public class BinaryPrinter {
public static void main(String[] args) {
System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
}
public static String binaryString( final int number, final int binaryDigits ) {
final String pattern = String.format( "%%0%dd", binaryDigits );
final String padding = String.format( pattern, 0 );
final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );
System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );
return response.substring( response.length() - binaryDigits );
}
}
%016s
?