Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal-to-binary conversion

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.

like image 827
UpCat Avatar asked Dec 17 '22 20:12

UpCat


2 Answers

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

System.out.println(Integer.toBinaryString(12))
like image 98
codaddict Avatar answered Jan 01 '23 22:01

codaddict


I assume you want to write your own code -- otherwise this is straightforward to do using methods from the standard Java library.

Some quick comments:

  • You can get rid of the res temp vars. Work directly on number (remember that Java passes parameters by value).
  • Shift is more efficient than division (number >>>= 1 instead of number /= 2), although the compiler should be able to optimize this anyway
  • You can avoid the modulus in decToBin if you just do array[k] = number & 1;
  • While you are at it, why not call getBinArray from decToBin directly? Then you can call decToBin with only one arg -- the value to convert.

Here is a slightly optimized version of your code:

public static int[] getBinArray(int number) {
    int length = 0;
    while (number != 0) {
        number >>>= 1;
        length++;
    }
    return new int[length];
}

public static int[] decToBin(int number) {
    int[] array = getBinArray(number);
    int k = array.length-1;
    while (number != 0)
    {
        array[k--] = number & 1;
        number >>>= 1;
    }
    return array;
}
like image 27
Grodriguez Avatar answered Jan 01 '23 21:01

Grodriguez