简体   繁体   English

这是什么错误?

[英]What's the error here?

int i = 10000;
Integer.toBinaryString(i);

How can I make the Integer.toBinaryString method return leading zeroes as well? 如何使Integer.toBinaryString方法也返回前导零? For example, for i = 1000 , I want 00000000000000000000001111101000 to appear, not 1111101000 . 例如,对于i = 1000 ,我希望显示00000000000000000000001111101000 ,而不是1111101000

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. 在这里,我选择了16位数字的宽度,您可以通过字符串中零的数目来调整宽度。

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). 请注意,如果i > 2^16 - 1可能会失败,那么您需要对此加以保护(32个零将是一种方法)。

EDIT 编辑

Here's a more complicated version which formats to the smallest of 8, 16, 24, or 32 bits which will contain the result: 这是一个更复杂的版本,其格式设置为包含结果的最小8位,16位,24位或32位:

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 ) );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM