-3

I'm making a project of converting decimal number into binary. But I have a problem that how can I convert any entered number into binary (I'm using array), here is my code:

    public void Decimal2Binary(int a)
{
    int result []=new int[8];
    for (int i = 7;i >=0; i--,a/=2) {
        result[i]=a%2;
}

I do not need it for just only 8-bit binary result, yet, I need it for any size.

  • Why don't you pass it as an argument? – Maroun Sep 04 '14 at 13:05
  • 1
    `Integer.toBinaryString()`? – icza Sep 04 '14 at 13:08
  • Duplicate of http://stackoverflow.com/questions/14784630/converting-decimal-to-binary-java?rq=1 , http://stackoverflow.com/questions/13147413/convert-decimal-to-binary?rq=1 , http://stackoverflow.com/questions/22008606/converting-decimal-to-binary-in-java-having-trouble-with-reversing-order?rq=1 , and (apart from that) not very clear. – Marco13 Sep 04 '14 at 13:15
  • Any size makes absolutely no sense in a strongly typed language where the primitive types are strictly defined by the JLS. – Durandal Sep 04 '14 at 16:09
  • There is no decimal here. Everything is already in binary. What you are really doing is separating the bits. – user207421 Apr 06 '17 at 23:46

2 Answers2

0

use this function Integer.toBinaryString(int)... and why do you want it to be in a array ? can't it be an array list or big decimal.

StackFlowed
  • 6,664
  • 1
  • 29
  • 45
0

You don't actually specify the output, but here goes.

assuming unsigned (as it looks like you have).

StringBuilder result = new StringBuilder();
while(a > 0) {
    result.append(a % 2);
    a = a / 2; // This will round down automatically. ;)
}

If you need to handle negative numbers, I would do bitwise comparisons using the & operator - you could also use >> for the division, but I am leaving that optimisation for the compiler to keep the source more readable.

obviously you could change that to any form of append

Guy Flavell
  • 151
  • 6
  • if you actually want it as a string output, I would suggest using the standard functionality, but if you want to control the bits in whatever forms you get them this gives you that control. – Guy Flavell Sep 04 '14 at 13:14