4

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.

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • 1
    Is this homework? If so, you should tag it as such. – Jim Garrison Nov 11 '10 at 19:27
  • @Jim: ["The homework tag...is now discouraged,"](http://meta.stackoverflow.com/q/10812) but, @ArtWorkAD, please (as always) follow [general guidelines](http://tinyurl.com/so-hints): state any special restrictions, show what you've tried so far, and ask about what specifically is confusing you. –  Nov 12 '10 at 14:09

4 Answers4

6

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

System.out.println(Integer.toBinaryString(12))
codaddict
  • 445,704
  • 82
  • 492
  • 529
3

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;
}
Grodriguez
  • 21,501
  • 10
  • 63
  • 107
  • can you describe the shift operator please – DarkLeafyGreen Nov 12 '10 at 09:04
  • 2
    @ArtWorkAD: The logical shift operator `>>>` shifts all bits in the operand to the right by the specified number of positions, inserting as many zero bits as necessary to fill the vacant positions in the left. Thus `number >>>= 1` shifts all bits one position to the right, inserting one zero bit as the MSB. See: http://en.wikipedia.org/wiki/Logical_shift – Grodriguez Nov 12 '10 at 09:47
  • thanks, and what do you mean with array[k--] = number & 1? whats the "?" ? – DarkLeafyGreen Nov 12 '10 at 09:52
  • @ArtWorkAD: Note that logical shift (`>>>`) is used here instead of arithmetic shift (`>>`). Arithmetic shift would preserve the sign bit, thus you would never reach the termination condition for the loop (`number` reaching zero). – Grodriguez Nov 12 '10 at 09:53
  • @ArtWorkAD: It is not a `?` but a `&`. That's the bitwise AND operator. The expression `number & 1` retains only the least significant bit of `number`. This will be 1 if the number is odd and 0 if it is even. – Grodriguez Nov 12 '10 at 09:56
2

If this isn't homework, no need to do it yourself. The following code should work:

BigInteger bigInt = new BigInteger(number);
String asString = bigInt.toString(2);

There might be more efficient ways, but this is certainly very readable and maintainable.

nojo
  • 1,065
  • 6
  • 12
1

There are some small things that you can improve:

  • You should define a "high-level" method that converts an int to an int[]. In the current code you have to mention the 12 two times, which is bad.
  • You should use a do { ... } while (number != 0) loop. Otherwise the number 0 will be represented by an empty array.
  • You should use x >>> 1 instead of x / 2, since that handles negative numbers correctly.
  • If you want to check that your code is correct, write another method that converts back from binary to int. Then you can check that binToDec(decToBin(12, ...)) == 12.
  • The method getBinArray should not be public, since it is only a helper method. You can either replace the public with private or just remove the public.
Roland Illig
  • 40,703
  • 10
  • 88
  • 121