Saltarin
Saltarin

Reputation: 1

Decimal to binary function in Java

I'm writing a function to convert an int number to their int numberbinary following this explanation: Suppose we wish to convert decimal 57 to binary. We begin by writing the positional values of the columns right to left until we reach a column whose positional value is greater than the decimal number. We don’t need that column, so we discard it. Thus, we first write:

Positional values: 64 32 16 8 4 2 1

Then we discard the column with positional value 64, leaving:

Positional values: 32 16 8 4 2 1

Next we work from the leftmost column to the right. We divide 32 into 57 and observe that there’s one 32 in 57 with a remainder of 25, so we write 1 in the 32 column. We divide 16 into 25 and observe that there’s one 16 in 25 with a remainder of 9 and write 1 in the 16 column. We divide 8 into 9 and observe that there’s one 8 in 9 with a remainder of 1. The next two columns each produce quotients of 0 when their positional values are divided into 1, so we write 0s in the 4 and 2 columns. Finally, 1 into 1 is 1, so we write 1 in the 1 column. This yields:

Positional values: 32 16 8 4 2 1 Symbol values: 1 1 1 0 0 1

I wrote the function trying to follow the footsteps of the explanation. When dec = 10 and c2 = 4, should not continue the while loop because 10 <= 4 is false, but the condition is taken as true. Could someone explain what has happened here?

public static int decimaltobinary(int dec){}{
    int bin = 0,it;
    int c1,c2;
    while(dec>0){
        it = 1;
        do{
            c2 = (int)Math.pow(2, it +1);
            c1 = (int)Math.pow(2, it);
        }while(dec <= c2 && dec < c1);
        bin += Math.pow(10, it - 1);
        dec = dec % c1;
    }
    return bin;
}

Upvotes: 0

Views: 171

Answers (1)

Atuos
Atuos

Reputation: 521

You can do it much easier if you don't need your own algorithm:

public int toBinary(int decimal) {
    String binaryString = Integer.toBinaryString(decimal);
    return Integer.parseInt(binaryString);
}

If you want to make your own algorithm, bit bashing would be easier. An int seems like a poor container for a binary representation of an integer, since you can only hold 9 bits.

public int toBinaryBitBashing(int decimal) {
    int bitCount = 6;
    int bit = 0;
    int binary = 0;
    int power = 1;
    for(int i=0; i<bitCount; ++i) {
        bit = (decimal >> i) & 1;
        binary += bit * power;
        power *= 10;
    }

    return binary;
}

Upvotes: 2

Related Questions