@@ -11,27 +11,58 @@ public class HexadecimalToDecimal {
11
11
*/
12
12
public String hexToDecimal (String hexaStr ) {
13
13
String hexaNumbers = "0123456789ABCDEF" ;
14
- int m , result = 0 ;
14
+ int m , result = 0 , decimalNumberBefore = 0 , power = -1 ;
15
+ Double decimalNumberAfter = 0.0 ;
15
16
char letter ;
16
17
String decimalStr ;
17
18
hexaStr = hexaStr .toUpperCase ();
18
-
19
- for (int i = 0 ; i < hexaStr .length () ; i ++) {
20
- /**
21
- * Letter will store the hexadecimal number as long as we loop through
22
- * the string
23
- */
24
- letter = hexaStr .charAt (i );
19
+ int pointPosition = hexaStr .indexOf ("." );
20
+ /**
21
+ * Check whether the number contains a float point or not
22
+ */
23
+ if ( pointPosition == -1 ) {
24
+ for (int i = 0 ; i < hexaStr .length () ; i ++) {
25
+ /**
26
+ * Letter will store the hexadecimal number as long as we loop through
27
+ * the string
28
+ */
29
+ letter = hexaStr .charAt (i );
25
30
26
- /**
27
- * m is the index of the number that we are looping through in the
28
- * hexaNumbers
29
- */
30
- m = hexaNumbers .indexOf (letter );
31
- result = 16 *result + m ;
32
- }
31
+ /**
32
+ * m is the index of the number that we are looping through in the
33
+ * hexaNumbers
34
+ */
35
+ m = hexaNumbers .indexOf (letter );
36
+ result = 16 *result + m ;
37
+ }
38
+ decimalStr = String .valueOf (result );
39
+
40
+ }
41
+ else {
42
+ for ( int i = 0 ; i < pointPosition ; i ++) {
43
+ letter = hexaStr .charAt (i );
44
+ m = hexaNumbers .indexOf (letter );
45
+ decimalNumberBefore = 16 *decimalNumberBefore + m ;
46
+ }
47
+
48
+ String decimalNumberBeforeStr = String .valueOf (decimalNumberBefore );
49
+
50
+ for ( int i = pointPosition +1 ; i < hexaStr .length () ; i ++) {
51
+ letter = hexaStr .charAt (i );
52
+ m = hexaNumbers .indexOf (letter );
53
+ decimalNumberAfter = (decimalNumberAfter + (Math .pow (16 , power ))*m );
54
+ power = power -1 ;
55
+ }
56
+ /**
57
+ * Retrieve the decimal part of the result
58
+ */
59
+ String decimalNumberAfterStr = String .valueOf (decimalNumberAfter );
60
+ int indexOfDecimal = decimalNumberAfterStr .indexOf ("." );
61
+ decimalNumberAfterStr = decimalNumberAfterStr .substring (indexOfDecimal );
62
+
63
+ decimalStr = decimalNumberBeforeStr + decimalNumberAfterStr ;
64
+ }
33
65
34
- decimalStr = String .valueOf (result );
35
- return decimalStr ;
66
+ return decimalStr ;
36
67
}
37
68
}
0 commit comments