joescull
joescull

Reputation: 1

Mathematically calculating decimal to binary (java)

I am having issue with my algorithms to convert a decimal number to a binary number without using parsing, this is the relevant section of code:

public static void dtb(){
    System.out.print("\nDenary number to convert?(lower than 255): "); //eight bit conversion
    int num = sc.nextInt();
    int decVal = 128;
    int saveNum = num; //save point for the first input
    int[] arr;
    arr = new int[8];
        do{
            if (num - decVal > 0){ //binary to decimal
                num =  num - decVal;
                arr[x] = 1;
            } else arr[x] = 0;
                decVal = decVal / 2;
                x++;
        } while (decVal != 1);
    System.out.print("\nBinary value of "+saveNum+" is: "+arr[0]+arr[1]+arr[2]+arr[3]+arr[4]+arr[5]+arr[6]+arr[7]);
}

x is declared initialized statically, therefore out of view.I also know where the error is but I cant work out the right way to do it, hence the ask for help. I am also fairly new so any help on other method will be appreciated. Thank you for any help. Example of output = (input=42) 00101000

Upvotes: 0

Views: 83

Answers (1)

rgettman
rgettman

Reputation: 178253

You need to compare whether num - decVal is greater than or equal to 0. Because you have >, you are missing the case then it's equal to 0 and you're missing a 1 bit.

if (num - decVal >= 0){ 

Also, you'll need to loop while decVal is not equal to 0, instead of 1, or else you'll miss the last bit on odd numbers.

} while (decVal != 0);

Output with changes:

Binary value of 42 is: 00101010
Binary value of 43 is: 00101011

Upvotes: 1

Related Questions