Java Integer to Binary Conversion

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to convert an integer to binary in Java. There are several methods to do this conversion, and we will cover the most commonly used methods.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/StringManipulationGroup -.-> java/stringbuffer_stringbuilder("`StringBuffer/StringBuilder`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/classes_objects -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/class_methods -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/modifiers -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/oop -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/wrapper_classes -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/identifier -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/stringbuffer_stringbuilder -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/arrays -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/data_types -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/for_loop -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/operators -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/output -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/strings -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/variables -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/while_loop -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/object_methods -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} java/system_methods -.-> lab-117748{{"`Java Integer to Binary Conversion`"}} end

Using toBinaryString() method

The toBinaryString() method is the easiest way to convert an integer to a binary string. This method is an Integer class method that returns a String after converting the int to binary.

public static String toBinaryString(int val)

Here val is the value to which we want to convert to the binary number system. This method will return the binary value in string format.

public class IntegerToBinaryConverter {
    public static void main(String[] args) {
        int val = 183;
        System.out.println("Value in binary system is: " + Integer.toBinaryString(val));
    }
}

Output: Value in binary system is: 10110111

Using Long Division Method

This method is completely mathematical. We declare an array of an integer of size 32 by considering 32-bit binary representation. Each time we divide a number by 2 and store the reminder inside the array of the integer. In the end, to get the result we traverse it in a reverse way.

public class IntegerToBinaryConverter {
    public static void main(String[] args) {
        int val = 183;
        int num[] = new int[32];
        int pos = 0;
        while (val > 0) {
            num[pos++] = val % 2;
            val = val / 2;
        }
        System.out.print("Value in binary system is: ");
        for (int i = pos - 1; i >= 0; i--) {
            System.out.print(num[i]);
        }
    }
}

Output: Value in binary system is: 10110111

Using Bit Manipulation

Using the right shift operator we can make any value into half, and since we are working on a bit level it is a very low-cost operation; and the rest of the things are the same as mentioned in the above example. At last, we are printing value using reverse the value which is stored in a StringBuilder object to make it in the binary form correctly.

public class IntegerToBinaryConverter {
    public static void main(String[] args) {
        int val = 183;
        StringBuilder binary = new StringBuilder(32);
        while (val > 0) {
            binary.append(val % 2);
            val >>= 1;
        }
        binary.reverse().toString();
        System.out.print("Value in binary system is: " + binary.reverse().toString());
    }
}

Output: Value in binary system is: 10110111

Using Integer.toString() Method

There is one more interesting way in java.lang.Integer class by using Integer.toString() method, which accepts the first argument as a number and the second as a radix (here radix is a base of number system) which can be 2 for Binary, 8 for Octal, 16 for Hexadecimal; in our case, we will set the radix to 2 for Binary number.

public class IntegerToBinaryConverter {
    public static void main(String[] args) {
        int val = 183;
        System.out.print("Value in binary system is: " + Integer.toString(val, 2));
    }
}

Output: Value in binary system is: 10110111

Summary

In this lab, we learned how to convert an integer to a binary number system in Java using four different methods. The first method is using the built-in toBinaryString() method, the second one using a long division method, the third one is using bit manipulation, and the fourth one is using Integer.toString() method.

Each method has its own advantages and disadvantages, and you can use the one that suits best according to your needs.