Java program to convert integer value into binary

Let’s learn java program to convert integer value into binary.

java program to convert integer value into binary

Java program to convert integer value into binary

To convert an integer to binary string in java first user enters an integer number as input.

Then using modulus and division operator given input is converted into binary. Here’s how to convert int to binary in java,

import java.util.Scanner;

public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the a number : ");
      num = sc.nextInt();
      // convert int to binary java
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}



Output:

Please enter the a number : 12
The binary conversion is : 1100


Here we are going to learn to convert integer value to binary using java lang.Integer.toBinaryString() method.

Also read – java decimal to binary method

This method returns the string representation of the unsigned integer value represented by the argument in binary (base 2).

import java.util.*;

public class IntToBinaryDemo
{
   public static void main(String[] args)
   {
      Integer num = new Integer(23);
      // integer.tobinarystring
      String strBinary = Integer.toBinaryString(num);
      System.out.println("tobinarystring : " + strBinary);
   }
}



Output:

tobinarystring : 10111


Also read – decimal to binary in java without array


binary to integer java

To convert binary to integer in java use Integer.parseInt() method. This method returns the integer represented by the string argument in the specified radix.

public class BinaryToIntegerExample 
{
   public static void main(String[] args)
   {
      String strBinary = "1001011";
      Integer value = Integer.parseInt(strBinary, 2);
      System.out.println("binary to integer java: " + value);
   }
}


Output:

binary to integer java: 75

java integer to binary string with leading zeros

To get binary string with leading zeros use format() method of class String. This method returns a formatted string using the specified format string and arguments.

The locale always used is the one returned by Locale.getDefault(). In the below example left pad of binary string has leading zeros.

public class IntegerToBinaryString
{
   public static String toBinaryString(int a, int len) 
   {
      if(len > 0) 
      {
         return String.format("%" + len + "s", Integer.toBinaryString(a)).replaceAll(" ", "0");
      }
      return null;
   }

   public static void main(String[] args) 
   {
      System.out.println(toBinaryString(100, 16));
   }
}


Output:

0000000001100100

Also read – java program to convert binary to decimal