Thursday, May 26, 2022

[Solved] How to convert Decimal to Binary Number in Java? Example Tutorial

Hello guys, how are you doing? I have been sharing a lot of programming interview questions and coding problems for practice in this blog. Earlier, I have shared 21 String programing questions, 100+ data structure questions, and 20 System design questions and this week's programming exercise is to write a program to convert a decimal number to binary in Java. It's a simple exercise for beginners who have just started learning the Java programming language. Decimal numbers are base 10 numbers, which means there are exactly 10 digits to represent a number, starting from 0 to 9, on the other hand, the binary number system has just two digits 0 and 1, which is known as bits. 

Binary numbers have a lot of use in the digital world, in fact, binary is the language of computers where 0 and 1 represent true/false, on/off, and becomes key for logic formation. In order to convert a decimal number into binary, we will use a modules operator in Java, represented by a percentage sign (%).

This is also known as a remainder operator because it returns the remainder of a division operation, for example, 5%,2 will return 1 while 7%4 will return 3.

Since binary is a base 2 number system, we will divide each digit of decimal number with 2 and collect the remainder. The logic of converting a decimal number to binary is encapsulated inside toBinary(int number) method, which takes a decimal number and returns a byte array containing bits of binary equivalent.

By the way, you can use the technique mentioned in this article to also convert a decimal number to octal and hexadecimal systems, but there are a couple of more ways to do that, as shown in this article.




Java Program to Convert a Decimal Number to Binary in Java

Here is our complete Java program, which takes a decimal number as input from the user and converts it to binary format, after that it displays it on the console. There are two methods in the code, the first one is toBinary() and the second one is printBinary(), the former converts a decimal number to binary while later prints it. I have also created a third method called convert() which combines these two methods.

The logic of how to convert a decimal to binary is written on toBinary() method, if you look at that method, we first create a copy of the input number, which you should always do if you intend to modify input passed by the user. 

There is a while loop, which runs until the decimal number is greater than zero. In each pass, we do two operations, first using division operator / and second using remainder operator %

In each pass, the number is reduced in half.  Just like a/10 is used to remove the last digit from the number and a%10 is used to get the last digit,  a/20 removes the last bit and a%2 gives you the last bit. 

All these bits are stored in a byte array, whose size is 32 because the size of int primitive is 32-bit in Java. PrintBinary() is a simple method to print binary arrays in Java.

import java.util.Scanner;
import java.util.concurrent.TimeUnit;
 
/**
 * Java program to convert Decimal number into Binary in Java.
 *
 * @author Javin
 */
public class Testing {
 
    public static void main(String args[]) {
 
        Scanner sc = new Scanner(System.in);
        int number = Integer.MAX_VALUE;
 
        while (number != 0) {
            // Ask user to enter number for decimal to binary conversion
            System.out.println("\nEnter a decimal number to convert into binary format");
 
            number = sc.nextInt();
 
            // one way to convert decimal number to binary in Java
            byte[] bits = toBinary(number);
            printBinary(bits);
 
            // combined conversion and printing part in one method
            convert(number);
 
        }
        sc.close();
 
    }
 
    /*
     * Java Method to convert decimal to binary
     */
    public static byte[] toBinary(int number) {
        byte[] binary = new byte[32];
        int index = 0;
        int copyOfInput = number;
        while (copyOfInput > 0) {
            binary[index++] = (byte) (copyOfInput % 2);
            copyOfInput = copyOfInput / 2;
        }
 
        return binary;
    }
 
    /*
     * Print number in binary format
     */
    public static void printBinary(byte[] binary) {
        for (int i = binary.length - 1; i >= 0; i--) {
            System.out.print(binary[i]);
        }
    }
 
    /*
     * Combination of previous two method to convert and print binary numbers
     */
    public static void convert(int input) {
        int copyOfInput = input;
        StringBuilder sb = new StringBuilder();
 
        while (copyOfInput > 0) {
            byte bit = (byte) (copyOfInput % 2);
            sb.append(bit);
            copyOfInput = copyOfInput / 2;
        }
 
        System.out.printf("\nDecimal number %d in Binary format is %s %n", 
                            input, sb.toString());
    }
 
}
 
Output
 
Enter a decimal number to convert into binary format
33
00000000000000000000000000100001
Decimal number 33 in Binary format is 100001
 
Enter a decimal number to convert into binary format
45
00000000000000000000000000101101
Decimal number 45 in Binary format is 101101


That's all on How to convert a decimal number to binary in Java. You can write similar programs to convert decimal numbers to octal or hexadecimal format. All you need to change is core logic, where instead of dividing by 2 you need to divide by 8 or 16, depending upon whether you are converting into Octal or Hexadecimal. 

One more thing which you need to take care of in the case of base 16 is incorporating additional characters like from A to F to represent 10 to 15. On the reverse side, if you want to convert Hexadecimal numbers to decimal, octal or binary, you can see this tutorial.

   Other Java Coding Problems for Practice

Thanks for reading this article so far. If you like this solution of converting a decimal number to binary in Java and my explanation then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 
   

3 comments:

  1. Hi..!! I couldn't understand below line of code:
    System.out.printf("\nDecimal number %d in Binary format is %s %n", input, sb.toString());
    like: %d, %s, %n what is this and how is it working?? is this any new feature?? if then please provide me the link where you have explained these new things..!! thanks

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.