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
raja
Published on 21-Dec-2018 11:28:06
Advertisements