|
@@ -0,0 +1,64 @@
|
|
1
|
+
|
|
2
|
+/**
|
|
3
|
+ * Write a description of class NumSystemsConverter here.
|
|
4
|
+ *
|
|
5
|
+ * @author (your name)
|
|
6
|
+ * @version (a version number or a date)
|
|
7
|
+ */
|
|
8
|
+public class NumSystemsConverter
|
|
9
|
+{
|
|
10
|
+ // Decimal to binary converter
|
|
11
|
+
|
|
12
|
+public String toBinary(double d, int precision) {
|
|
13
|
+ long wholePart = (long) d;
|
|
14
|
+ return wholeToBinary(wholePart) + '.' + fractionalToBinary(d - wholePart, precision);
|
|
15
|
+}
|
|
16
|
+
|
|
17
|
+private String wholeToBinary(long l) {
|
|
18
|
+ return Long.toBinaryString(l);
|
|
19
|
+}
|
|
20
|
+
|
|
21
|
+private String fractionalToBinary(double num, int precision) {
|
|
22
|
+ StringBuilder binary = new StringBuilder();
|
|
23
|
+ while (num > 0 && binary.length() < precision) {
|
|
24
|
+ double r = num * 2;
|
|
25
|
+ if (r >= 1) {
|
|
26
|
+ binary.append(1);
|
|
27
|
+ num = r - 1;
|
|
28
|
+ } else {
|
|
29
|
+ binary.append(0);
|
|
30
|
+ num = r;
|
|
31
|
+ }
|
|
32
|
+ }
|
|
33
|
+ return binary.toString();
|
|
34
|
+}
|
|
35
|
+
|
|
36
|
+// display mode is sent along with displayNumber, could also be defined globally)
|
|
37
|
+
|
|
38
|
+public class String updateDisplayNumber(double displayNumber,int mode){
|
|
39
|
+ String str="";
|
|
40
|
+switch(mode) {
|
|
41
|
+ case 1:{
|
|
42
|
+ str=Double.toString(displayNumber);
|
|
43
|
+ break;
|
|
44
|
+ }
|
|
45
|
+ case 2:{
|
|
46
|
+ // toBinary takes number to convert and precision
|
|
47
|
+ str=toBinary(displayNumber,2);
|
|
48
|
+ break;
|
|
49
|
+ }
|
|
50
|
+ case 3:{
|
|
51
|
+ str=Double.toHexString(displayNumber);
|
|
52
|
+ break;
|
|
53
|
+ }
|
|
54
|
+ // OCTAL CONVERSION
|
|
55
|
+ // case 4:{
|
|
56
|
+ // double fraction = (int)((displayNumber%1)+0.5);
|
|
57
|
+ // double integral = (int)displayNumber-fraction;
|
|
58
|
+ // String str=Integer.toOctalString(integral)+"."+Integer.toOctalString(fraction);
|
|
59
|
+ // break;
|
|
60
|
+ // }
|
|
61
|
+}
|
|
62
|
+ return str;
|
|
63
|
+}
|
|
64
|
+}
|