0

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

Me Myself
  • 185
  • 2
  • 11
  • 3
    Does this answer your question? [How can I pad an integer with zeros on the left?](https://stackoverflow.com/questions/473282/how-can-i-pad-an-integer-with-zeros-on-the-left) (maybe not an exact duplicate, but still). – Federico klez Culloca Jun 29 '20 at 10:07
  • 1
    Does this answer your question? [Java convert from decimal to 8-bit binary](https://stackoverflow.com/questions/48952307/java-convert-from-decimal-to-8-bit-binary) – Sudhir Ojha Jun 29 '20 at 10:11
  • Can you try if (n <= 63) { for (int i = 8; i >= 0; i--) { System.out.print(binary[i]); } } – Sabareesh Muralidharan Jun 29 '20 at 10:18
  • Out of curiosity (and unrelated to your problem), if you need an 8-bit binary number, why are you allocating an array with 40 elements? – Federico klez Culloca Jun 29 '20 at 10:31

3 Answers3

0

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

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
dhakalkumar
  • 161
  • 1
  • 3
  • 14
0

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.

user13784117
  • 1,124
  • 4
  • 4
-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 ");
}
George R
  • 484
  • 6
  • 19