Decimal-to-binary conversion

Upvote picture Upvote · Nov 11, 2010 · Viewed 12.1k times · Source

I want to convert decimal numbers to binary numbers. I want to store them in an array. First I need to create an array that has a certain length so that I can store the binary numbers. After that I perform the conversion, here is how I do it:

public class Aufg3 {
    public static void main(String[] args) {
        int[] test = decToBin(12, getBinArray(12));
        for(int i = 0; i < test.length; i++){
            System.out.println(test[i]);
        }
    }

    public static int[] getBinArray(int number){
        int res = number, length = 0;
        while(res != 0){        
            res /= 2;
                    length++;
        }
        return new int[length];
    }

    public static int[] decToBin(int number, int[] array){
        int res = number, k = array.length-1;
        while(res != 0){
            if(res%2 == 0){
                array[k] = 0;
            }else{
                array[k] = 1;
            }
            k--;
            res /= 2;
        }
        return array;
    }
}

Is there anything to improve? It should print 1100 for input of 12.

Answer

codaddict picture codaddict · Nov 11, 2010

Why not just use the toBinaryString method of the Integer class:

System.out.println(Integer.toBinaryString(12))