-
Notifications
You must be signed in to change notification settings - Fork 0
/
IEEEBinaryToDecimalCalculator.java
89 lines (81 loc) · 2.98 KB
/
IEEEBinaryToDecimalCalculator.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//********************************************************************************************************************\\
//--------------------------------------IEEE-754 binary to decimal convertor------------------------------------------\\
//********************************************************************************************************************\\
package com.company;
import java.util.Scanner;
class BinaryToDecimal {
static double convertExponent(String st) {
int len = st.length();
String exponent = "";
// taking out exponent bits to calculate its value
if (len == 32) {
exponent = st.substring(1, 9);
}
if (len == 64) {
exponent = st.substring(1, 12);
}
double exp = 0;
StringBuilder stValue = new StringBuilder();
for (int i = 0; i < exponent.length(); i++) {
stValue.insert(0, exponent.charAt(i));
}
for (int i = 0; i < stValue.length(); i++) {
if (stValue.charAt(i) == '1') {
exp = exp + 1 * (Math.pow(2, i));
}
}
// subtracting respective value of bias for 32-bits(127) & 64-bits(1023)
if (len == 32) {
exp = (int) (exp - 127);
}
if (len == 64) {
exp = (int) (exp - 1023);
}
System.out.println("exponent : " + exp);
return exp;
}
static double convertFraction(String st) {
String fraction = "";
int length = st.length();
if (length == 32) {
fraction = st.substring(9);
}
if (length == 64) {
fraction = st.substring(12);
}
double frac = 0;
int pow;
for (int i = 0; i < fraction.length(); i++) {
if (fraction.charAt(i) == '1') {
pow = i + 1;
frac = frac + 1 * (1 / Math.pow(2, pow));
}
}
frac = 1 + frac;
System.out.println("fraction : " + frac);
return frac;
}
}
public class Basics {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
System.out.print("enter 32-bit or 64-bits floating point number: ");
String num = number.next();
int numOfBits = num.length();
double finalFraction;
if (numOfBits == 32 || numOfBits == 64) {
double fracValue = BinaryToDecimal.convertFraction(num);
double expValue = BinaryToDecimal.convertExponent(num);
if (num.charAt(0) == '1') {
finalFraction = fracValue - (2 * fracValue);
} else {
finalFraction = fracValue;
}
// Resultant = FractionPart x Base^Exponent
double result = finalFraction * (Math.pow(2, expValue));
System.out.println("resultant decimal number: " + result);
} else {
System.out.println("number of bits are not equal to 32 or 64! enter a 32-bits or 64-bits number");
}
}
}