英文:
Print 8 bit binary conversion in java
问题
我只是试图在Java中制作一个十进制转二进制的转换器,我想要显示的效果应该像这样:
二进制41为00101001
但是,这里是我刚刚制作的显示效果:
二进制41为:101001
这是我的代码:
public void convertBinary(int num){
int binary[] = new int[40];
int index = 0;
while(num > 0){
binary[index++] = num % 2;
num/=2;
}
for(int i = index-1; i >= 0; i--){
System.out.print(binary[i]);
}
}
我该怎么做,才能显示8位二进制数?非常感谢您给我的所有答案,谢谢。
英文:
i'm just trying to make a decimal to binary converter in java, what i want to display is suppose to be like this:
Binary 41 is 00101001
But, here's display what i just made:
Binary 41 is: 101001
And here's my code:
public void convertBinary(int num){
int binary[] = new int[40];
int index = 0;
while(num > 0){
binary[index++] = num % 2;
num/=2;
}
for(int i = index-1; i >= 0; i--){
System.out.print(binary[i]);
}
What can i do, to make a display 8 bit binary? I appreciate it so much for all answer you gave to me, thank you
答案1
得分: 0
使用以下代码:
System.out.format("%08d%n", binary[i]);
而不是:
System.out.print(binary[i]);
System.out.format("%08d%n", binary[i]);
中的 "%08d%n"
将输出格式化为 8 位整数。
注意:
以下是更多示例:
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
英文:
Use
System.out.format("%08d%n", binary[i]);
instead of
System.out.print(binary[i]);
The "%08d%n"
in System.out.format("%08d%n", binary[i]);
formats the output as 8 digit integer.
Note:
Here are some more examples:
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
答案2
得分: 0
如果 num
保证小于 256,对于您现有的代码来说,最简单的改变是将循环条件改为 index < 8
while(index < 8){
binary[index++] = num % 2;
num/=2;
}
这直接表达了希望得到8位数的愿望。也就是说,您只需要在转换所有非零位时停止。
英文:
If num
is guaranteed to be less than 256, the simplest change for your existing code is to change the loop condition to index < 8
while(index < 8){
binary[index++] = num % 2;
num/=2;
}
This directly expresses the desire to have 8 digits. That is, you simply do not stop when you have converted all non-zero bits.
答案3
得分: -1
int t;
byte val = 123;
for(t = 128; t > 0; t = t/2){
if((val & t) != 0) System.out.print("1 ");
else System.out.print("0 ");
}
英文:
int t;
byte val = 123;
for(t = 128; t > 0; t = t/2){
if((val & t) != 0) System.out.print("1 ");
else System.out.print("0 ");
}
专注分享java语言的经验与见解,让所有开发者获益!
评论