Convert Decimal to Binary in Java

In this post, you will see how to convert Decimal to Binary in Java using the following ways:

  • Using toBinaryString() method
  • With custom logic

Convert Decimal to Binary in Java using the toBinaryString() method

There is a toBinaryString() method of the Integer class that we can use to get the Binary String of a Decimal number.

Example

class Test {

  public static void main(String[] args) {

    System.out.println(Integer.toBinaryString(48));
    System.out.println(Integer.toBinaryString(258));
    System.out.println(Integer.toBinaryString(1284));
  }
}
Output: 110000 100000010 10100000100

Convert Decimal to Binary with custom logic

We can implement custom logic to convert Decimal to Binary, like in the following example:

class Test {

  public static void main(String[] args) {

    System.out.println(getBinary(48));
    System.out.println(getBinary(258));
    System.out.println(getBinary(1284));
  }

  private static String getBinary(int number) {
    int[] binary = new int[40];
    int index = 0;
    StringBuilder binaryString = new StringBuilder();

    while (number > 0) {
      binary[index++] = number % 2;
      number = number / 2;
    }

    for (int i = index - 1; i >= 0; i--) {
      binaryString.append(binary[i]);
    }

    return binaryString.toString();
  }
}
Output: 110000 100000010 10100000100
 
The above code example demonstrates how to convert an integer input to its corresponding binary representation as a string. It uses a while loop to divide the input number by 2 and store each remainder in an array. It then uses a for loop to iterate through the array in reverse and append each digit to a string builder object. The final binary representation is returned as a string.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *