1

I am trying to to calculate binary value of the decimal variable, assign it binary array and print out value of binary array. I don't know where I am doing wrong. This is what is supposed to do; decimal -> 3 will print binary -> [0, 0, 0, 0, 0, 0, 1, 1]

here is what I did so far, but when I output, I see [I@7852e922.

import java.util.*;

class Main {
  public static void main(String[] args) {

    int[] binary = new int[8];
   int decimal = 3;

   String binaryString = Integer.toBinaryString(decimal);
   int num = Integer.parseInt(binaryString);
   int length = String.valueOf(num).length();
   while(length<8) {
       binaryString = Integer.toString(0) + binaryString;
       length++;
   }
   System.out.println(binaryString);
   int[] binaryInArray = new int[length];
   for(int i=0; i<length; i++) {
       binaryInArray[i] = Integer.parseInt(binaryString);
   }
   System.out.println(binaryInArray);

    } 


}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Alex
  • 37
  • 7
  • Try `System.out.println(Arrays.toString(binaryInArray))` – Mohammad C Oct 18 '18 at 02:18
  • yes, that's what I did after someone shared similar post but it shows [11, 11, 11, 11, 11, 11, 11, 11] this now, it supposed to show [0,0,0,0,0,0,1,1] – Alex Oct 18 '18 at 02:24
  • That's because the logic in your code is wrong. Gimme a sec i shall jump on laptop and edit your post with my untested answer. May take a while. – Mohammad C Oct 18 '18 at 02:24
  • No problem, will wait – Alex Oct 18 '18 at 02:44
  • I have a solution but upon testing i realised you probably want it to always be 8 bit. What i did was if its 3 would print [1 , 1] or 5 would be [1, 0, 1] . Did it so you aren't wasting memory also will work with any number. Is that okay or you need 8 bits. If so what should happen if number is over 8 bits like 256. – Mohammad C Oct 18 '18 at 02:49
  • Hey. I have edited with solution. The edit may take a while to come as it is pending review. I have included both solutions. Now i will go back to sleep. Any questions comment. I shall see in morning. – Mohammad C Oct 18 '18 at 03:02
  • I just want to use for specific bits, example 8 bits – Alex Oct 18 '18 at 03:08
  • if you can seet the edit yet. heres a link to a paste. https://pastecode.xyz/view/dc8255c2 – Mohammad C Oct 18 '18 at 03:10
  • Thank you so much @noyanc, that's exactly what I wanted for 8 bits. Thank you again, – Alex Oct 18 '18 at 03:16
  • No worries. I have updated the paste. Use the new link, https://pastecode.xyz/view/881de5d9. Im glad i was able to help and sorry someone was in a hurry in closing your question. – Mohammad C Oct 18 '18 at 03:18

0 Answers0