Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

java program for binary number to decimal

0 votes
asked Feb 4, 2020 by anonymous

2 Answers

+1 vote
answered Feb 4, 2020 by yaswanth katta
import java.io.*;
import java.util.*;

class Main{
  public static void main(String args[]){
    Scanner input=new Scanner(System.in);
    System.out.print("Enter a binary number: ");
    String binary=input.nextLine();
    
    int decimal=Integer.parseInt(binary,2);   // Converting binary to decimal
    System.out.println(binary+" = "+decimal);
  }
}
0 votes
answered Feb 4, 2020 by yaswanth katta
import java.io.*;
import java.util.*;

public class Main{    
  public static int getDecimal(int binary){  
      int decimal = 0;  
      int n = 0;  
      while(true){  
        if(binary == 0){  
          break;  
        } else {  
            int temp = binary%10;  
            decimal += temp*Math.pow(2, n);  
            binary = binary/10;  
             n++;  
        }  
      }  
    return decimal;  
}  
public static void main(String args[]){    
    Scanner input=new Scanner(System.in);
    System.out.print("Enter binary number: ");
    int binary=input.nextInt();
    
    int decimal=getDecimal(binary);
    System.out.println(binary+" = "+decimal);
  }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...