Google Add

Search

Java Program to Convert Binary to Decimal Number

Write a java program to convert binary to decimal number. In this tutorial, we are going to write a program which takes an input binary number and convert them into decimal number.

How to Convert Binary to Decimal Number


Let's assume, we have to convert 1000 to decimal number.

Decimal Number Conversion : 1 * 23   + 0 * 2 2   +  0 * 2 +  0 * 2 0 = 8

In this way, we can convert any binary number to decimal number.


Java program to find largest number in an array

C program to convert binary to decimal number



Java Program to Convert Binary to Decimal Number


Java Program to Convert Binary to Decimal Number


We have discussed an algorithm to convert binary to decimal number. Let's write a code to implement them.


import java.util.Scanner;

public class BinaryToDecimal {

  public static void main(String[] args) {
  
    Scanner in = new Scanner(System.in);

    //Input binary number
    System.out.println("Enter a binary number");
    Long num = in.nextLong();
  
    Long count = 0L, sum = 0L, rem = 0L;
  
    //Whether a number is greater than 0
    while(num > 0) {

      //find remainder
      rem = num % 10;
   
      //In case of binary number,
     //Remainder should be either 0 or 1
     if(rem == 0 || rem == 1) {
    
        sum = (long) (sum + rem * Math.pow(2, count));
        num = num / 10;
    
      } else {
        System.out.println("Invalid binary number");
        break;
      }
   
      count++;
   }

   System.out.println(" Decimal number is " + sum);
 }

}


Output



Java Program

Java program to count number of digits in a number

Java program to check whether a number is palindrome or not

No comments:

Post a Comment