Java lang.Integer.toBinaryString() method


The java.lang.Integer.toBinaryString() method returns a string representation of the integer argument as an unsigned integer in base 2.

Example

Following is an example to implement the toBinaryString() method in Java −

import java.lang.*;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 170;
      System.out.println("Number = " + i);
      /* returns the string representation of the unsigned integer value
      represented by the argument in binary (base 2) */
      System.out.println("Binary is " + Integer.toBinaryString(i));
      // returns the number of one-bits
      System.out.println("Num
   }
}

Output

Number = 170
Binary is 10101010
Number of one bits = 4

Let us see another example wherein we are considering a negative number −

Example

import java.lang.*;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = -35;
      System.out.println("Number = " + i);
      System.out.println("Binary is " + Integer.toBinaryString(i));
      System.out.println("Number of one bits = " + Integer.bitCount(i));
   }
}

Output

Number = -35
Binary is 11111111111111111111111111011101
Number of one bits = 30

Updated on: 24-Sep-2019

35 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements