-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinary2Decimal.java
More file actions
34 lines (32 loc) · 777 Bytes
/
Copy pathBinary2Decimal.java
File metadata and controls
34 lines (32 loc) · 777 Bytes
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
30
31
32
33
34
import java.util.Scanner;
class Binary2Decimal
{
public static int bin2Dec(String binaryString) throws NumberFormatException
{
int decimal = 0;
int strLength=binaryString.length();
for (int i = 0; i < strLength; i++)
{
if (binaryString.charAt(i) < '0' || binaryString.charAt(i) > '1')
{
throw new NumberFormatException("Not a binary number...");
}
decimal += (binaryString.charAt(i)-'0') * Math.pow(2, strLength-1-i);
}
return decimal;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Binary Value : ");
String str = input.nextLine();
try
{
System.out.println("Value = " + bin2Dec(str));
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}