在Java中打印8位二进制转换。

huangapple 未分类评论50阅读模式
英文:

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 &lt; 8

while(index &lt; 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 &gt; 0; t = t/2){
    if((val &amp; t) != 0) System.out.print(&quot;1 &quot;);
    else System.out.print(&quot;0 &quot;);
}

huangapple
  • 本文由 发表于 2020年6月29日 18:05:27
  • 转载请务必保留本文链接:https://java.coder-hub.com/62635751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定