Conversion programs in java

Question

Conversion programs in java. Convert the given binary number to decimal and decimal numbers to binary in an efficient way.

Binary and decimal number conversion

Program

import java.util.Scanner;
public class Binary {

public static void main(String ara[])
    { 
      Scanner s=new Scanner(System.in);
      int x = 5;

      System.out.println("Enter a binary number:");

      String n=s.nextLine();

      System.out.println("Decimal of given binary: Integer.parseInt(n,2));// binary to decimal

      System.out.println("Binary of 5: "+ Integer.toBinaryString(x)); // decimal to binary
    }
}

Explanation

  • We are converting decimal to binary and binary to a decimal using java.
  • Interegr.parseInt(String str) is the most commonly used method to convert String to int.
  • The String is a decimal format representation.
  • Internally, it invokes method Interegr.parseInt(String str, int radix) with radix value as 10.
  • By passing radix value as 2, we can convert Binary int representation String to int.
  • The same method can be applied for hexadecimal and octal with radix as  16,8 respectively.

 

You might also like…

Conversion program from number to words

Conversion program from decimal to binary

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x