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
 
That’s it!

Leave a Reply

Your email address will not be published.