Thursday, February 16, 2012

Tutorial: Decimal to Binary Converter in Java

Today, we will try to create a Java program that enables the user input a DECIMAL number then it will convert to its BINARY equivalent value. If you remember, I posted a tutorial about a Java program that converts a decimal number to its octal value (you can read here). There are lot of sites from the Internet that you can download the program source code but in this tutorial, I made my own code which is based from the rules in number system conversion.

To do this, we will again follow the rules in converting. Here are the rules in converting decimal to binary:

1. Get or write the whole decimal number and serve as the dividend.
2. Use the base of the Binary, which is 2 as the divisor.
3. Proceed to Division operation.
4. The quotient and the remainder will be written on the other side whether 0 or 1. If the quotient is a whole number, the write 0 in the remainder, else if the quotient is a decimal number, then write 1.
5. Get again the quotient and divide into its base, repeat step # 4.
6. Repeat step # 5 until the quotient will be zero.
7. Write the remainder from bottom to up, to form the binary equivalent.

The Output:

 

Now, as you can see the figure above, the user enters the Decimal number 25, then the program provides a number conversion simulation table that explains the process or concepts of the rules stated above. Rule # 7 indicates the final binary equivalent of the decimal number where the program must read the remainder from the bottom to top.

The Algorithm Base from the Rules:

Now to apply the rules in the actual program (starting from Rule # 1 to 6), this is what I did:

               do
                {
                    quotient = dividend/BASE;

                    if (dividend==1)
                    {
                        octal[x] = 1;
                    }
                    else
                    {
                        if((dividend%2)==0)
                        {
                            octal[x] = 0;
                        }

                        else
                        {

                            octal[x] = 1;
                        }
                    }
                    dividend = quotient;
                    System.out.println(dividend+"/"+BASE+"\t\t"+quotient+"\t\t"+octal[x]);
                    x++;
               }while(dividend!=0);

 Here, the line statement quotient = dividend/BASE explains rule # 1 to 3. Rule # 4 applies the nested-if statement wherein I used an array to store the series of 1's and 0's as the remainder. This is the real benefit of array data structure where you can store hundreds or even thousands of data using only one name. The line statement dividend = quotient applies Rule # 5 while Rule # 6 indicates the do-while statement. The simulation ends when the value of dividend reached 0.

So since the remainders (1's and 0's) are sequentially stored in the array starting from index 0 to the last index (the last index will be controlled by the variable x in the code above) . Now, to apply Rule # 5 where the remainders will be read from bottom to top, in the actual code we will assumed that the bottom remainder in the array assigned to the last index of the array. Therefore, we will create a code that will reads the last element (remainder) going to the first element. Here is the code I made:

                for (temp = x-1;temp >= 0;temp--)
                {
                    System.out.print(octal[temp]);
                }

In this code, I used a for loop to reads the remainders in the array. I created a temp variable that controls the index of the element in the array.


The Program Source Code:

/* Autor: Vilchor G. Perdido
 * Project: DecimalToBinaryConverter v.1.0
 * Date: February 15, 2012
 */

import java.util.*;

public class DecimalToBinaryConverter
{
    public static void main(String[] args)
    {
        Scanner read = new Scanner(System.in);
        int quotient = 0;
        final int BASE = 2;
        String choice = "";
        char sagot = ' ';

        System.out.println("======================================");
        System.out.println("DECIMAL TO BINARY CONVERTER PROGRAM");
        System.out.println("======================================");

        do {
            try {
                System.out.println("Please input DECIMAL number to convert:");
                int whole = read.nextInt();

                int temp=0;
                int dividend=0;
                int octal[] = new int[100];

                int x=0;
                System.out.println("\nThe Number Conversion Simulation Table");

                dividend = whole;
                System.out.println("\nDivision\tQuotient\tRemainder");
                do
                {
                    quotient = dividend/BASE;

                    if (dividend==1)
                    {
                        octal[x] = 1;
                    }
                    else
                    {
                        if((dividend%2)==0)
                        {
                            octal[x] = 0;
                        }

                        else
                        {

                            octal[x] = 1;
                        }
                    }
                    dividend = quotient;
                    System.out.println(dividend+"/"+BASE+"\t\t"+quotient+"\t\t"+octal[x]);
                    x++;

                }while(dividend!=0);

                System.out.print("\nThe BINARY value is ---> ");
                for (temp = x-1;temp >= 0;temp--)
                {
                    System.out.print(octal[temp]);
                }
            }

            catch(InputMismatchException e)
            {
                read = new Scanner(System.in);
                System.out.println("=========WARNING MESSAGE!!!==========");
                System.out.println("\tWrong or Incorrect Input");
                System.out.println("=====================================");
            }

            System.out.println("\n\nWhat do you want? Convert again?");
            System.out.println("Press Y or y to continue or any key to quit.");
            System.out.print("Confirm choice:");
            choice = read.next();
            sagot = choice.charAt(0);
            System.out.println("");

        } while(sagot=='Y' || sagot=='y');
        System.out.println("Program terminated.....");
    }
}


In addition, I also put some spicy ingredients in the program to make it more formal. I used the try and catch statements to handle errors such as when the user enters a non-decimal number to be converted. In the program, a warning message will appear if the user do so (see figure below).

 

Try it now guys. It's FREE. Just visit this blog regularly for more fun Java programs. Next project ---> the Decimal to Hexadecimal Converter. Coming soon...

Like Us on Facebook

Related Posts Plugin for WordPress, Blogger...