Convert Integer To Binary In Java

Sharing is healthy !!

Hey guys!! Welcome to flower brackets blog. Today we are going to convert integer to binary in java.

In the example below I have created a method which converts a number to binary in java.

Now let’s see the example,

example: Convert Integer To Binary In Java

import java.util.Scanner;

public class IntToBinary
{
   public static void main(String[] args)
   {
      int number = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter an integer : ");
      number = sc.nextInt(); 
      convertToBinary(number);
      sc.close();
   }
 
   public static void convertToBinary(int num)
   {
      String str = "";
      for(int a = 0; a < 8; a++)
      {
         if(num % 2 == 1)
         {
            str = "1" + str;
         }
         if(num % 2 == 0)
         {
            str = "0" + str;
         }
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
   }
}

Output:

Please enter an integer : 14
The binary conversion is : 00001110


using while loop

Now we are going to convert int to binary in java using while loop. So let’s see the code implementation,

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();
      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 : 23
The binary conversion is : 10111


using Integer.toBinaryString()

Here we are going to learn converting integer to binary in java using Integer.toBinaryString() and also we will be counting number of one bits in the given integer.

Also Read – Convert Decimal to Binary Java Example

Let’s see an example,

import java.util.Scanner;

public class IntToBinaryDemo
{
   public static void main(String[] args)
   {
      int number;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the a number : ");
      number = sc.nextInt(); 
      System.out.println("The Binary conversion is : " + Integer.toBinaryString(number)); 
      System.out.println("The number of 1 bits in " + number + " is : "+ Integer.bitCount(number));
      sc.close();
   }
}

Output:

Please enter the a number : 23
The Binary conversion is : 10111
The number of 1 bits in 23 is : 4


conclusion

That’s it guys. This is all about java binary representation of integer. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Sharing is healthy !!