Java Program to Parse and Format a Number into Binary


To parse a number to binary, use the Integer.parseInt() method with binary as the first parameter and radix as 2 passed as a 2nd parameter.

Let’s say the following is our integer −

int val = 566;

Now, use the Integer.parseInt() method −

val = Integer.parseInt("11111111", 2);

Using the Integer.toString() method will format the above value into binary −

String str = Integer.toString(val, 2);

The following is an example −

Example

 Live Demo

public class Demo {
   public static void main(String []args){
      int val = 566;
      val = Integer.parseInt("11111111", 2);
      System.out.println(val);
      String str = Integer.toString(val, 2);
      System.out.println(str);
   }
}

Output

255
11111111

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements