用字符串连接零

时间:2014-03-24 18:26:17

标签: java string

我正在尝试将零附加到字符串以使其成为32位数。但输出不显示附加的零。为什么会这样?

    System.out.print("\nEnter the linear Address (32bit) :\t");
    String linear_hex= sc.nextLine();
    String linear_bin= Integer.toBinaryString(Integer.parseInt(linear_hex,16));

    if(linear_bin.length() != 32)
    {

        for(int i= linear_bin.length(); i<=32; i++)
            linear_bin= 0+linear_bin;
    }

输出:

Enter the linear Address (32bit) :  12345678
Linear Address = 10010001101000101011001111000

我还尝试了linear_bin= "0"+linear_bin;"0".concat(linear_bin);,但输出仍然相同。

1 个答案:

答案 0 :(得分:5)

您的代码适用于我:

System.out.print("\nEnter the linear Address (32bit) :\t");
    Scanner sc = new Scanner(System.in);
    String linear_hex= sc.nextLine();
    String linear_bin= Integer.toBinaryString(Integer.parseInt(linear_hex,16));

    if(linear_bin.length() != 32) {         
        // Should be i < 32 instead of i <= 32, else you end up with an extra 0
        // Also consider using StringBuilder instead of String concatenation here
        for(int i= linear_bin.length(); i < 32; i++)
            linear_bin= 0+linear_bin;
    }
    System.out.println(linear_bin);

输入:

123456

输出:

00000000000100100011010001010110

但是,您可以使用String.format()方法更轻松地实现此目的。删除if块,并添加此print语句:

System.out.println(String.format("%32s", linear_bin).replace(' ', '0'));