There are two following ways to convert binary number to decimal number:
1) Using Integer.parseInt() method of Integer class.
2) Do conversion by writing your own logic without using any predefined methods.
Method 1: Binary to Decimal conversion using Integer.parseInt() method
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Scanner; class BinaryToDecimal { public static void main(String args[]){ Scanner input = new Scanner( System.in ); System.out.print("Enter a binary number: "); String binaryString =input.nextLine(); System.out.println("Output: "+Integer.parseInt(binaryString,2)); } } |
Method 2: Conversion without using parseInt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Details { public int BinaryToDecimal(int binaryNumber){ int decimal = 0; int p = 0; while(true){ if(binaryNumber == 0){ break; } else { int temp = binaryNumber%10; decimal += temp*Math.pow(2, p); binaryNumber = binaryNumber/10; p++; } } return decimal; } public static void main(String args[]){ Details obj = new Details(); System.out.println("110 --> "+obj.BinaryToDecimal(110)); System.out.println("1101 --> "+obj.BinaryToDecimal(1101)); System.out.println("100 --> "+obj.BinaryToDecimal(100)); System.out.println("110111 --> "+obj.BinaryToDecimal(110111)); } } |