我试图将零附加到字符串,使其成为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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Enter the linear Address (32bit) : 12345678
Linear Address = 10010001101000101011001111000
Run Code Online (Sandbox Code Playgroud)
我也试过linear_bin= "0"+linear_bin;,"0".concat(linear_bin);但输出仍然是一样的.
你的代码对我来说很好:
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);
Run Code Online (Sandbox Code Playgroud)
输入:
123456
Run Code Online (Sandbox Code Playgroud)
输出:
00000000000100100011010001010110
Run Code Online (Sandbox Code Playgroud)
但是,您可以使用String.format()方法更轻松地实现此目的.删除if块,并添加此print语句:
System.out.println(String.format("%32s", linear_bin).replace(' ', '0'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |