Java Reference
In-Depth Information
A brute-force approach is to convert each hex character into a decimal number, multiply it by
16
i
for a hex digit at the
i
's position, and then add all the items together to obtain the equiva-
lent decimal value for the hex number.
Note that
16
n
16
n
-
1
16
n
-
2
16
1
16
0
h
n
*
+
h
n
-
1
*
+
h
n
-
2
*
+ c +
h
1
*
+
h
0
*
=
(
c
((
h
n
*
16
+
h
n
-
1)
*
16
+
h
n
-
2)
*
16
+ c +
h
1
)
*
16
+
h
0
This observation, known as the Horner's algorithm, leads to the following efficient code for
converting a hex string to a decimal number:
int
decimalValue =
0
;
for
(
int
i =
0
; i < hex.length(); i++) {
char
hexChar = hex.charAt(i);
decimalValue = decimalValue *
16
+ hexCharToDecimal(hexChar);
}
Here is a trace of the algorithm for hex number
AB8C
:
hexCharToDecimal
(hexChar)
i
hexChar
decimalValue
before the loop
0
after the 1st iteration
0
A
10
10
after the 2nd iteration
1
B
11
10 * 16 + 11
after the 3rd iteration
2
8
8
(10 * 16 + 11) * 16 + 8
after the 4th iteration
3
C
12
((10 * 16 + 11)
* 16 + 8) * 16 + 12
Listing 6.8 gives the complete program.
L
ISTING
6.8
Hex2Dec.java
1
import
java.util.Scanner;
2
3
public class
Hex2Dec {
4
/** Main method */
5
public static void
main(String[] args) {
6
// Create a Scanner
7 Scanner input =
new
Scanner(System.in);
8
9
// Prompt the user to enter a string
10 System.out.print(
"Enter a hex number: "
);
11 String hex = input.nextLine();
12
13 System.out.println(
"The decimal value for hex number "
14 + hex +
" is "
+ hexToDecimal(hex.toUpperCase()));
15 }
16
17
public static int
hexToDecimal(String hex) {
18
int
decimalValue =
0
;
19
for
(
int
i =
0
; i < hex.length(); i++) {
20
char
hexChar = hex.charAt(i);
21 decimalValue = decimalValue *
16
+ hexCharToDecimal(hexChar);
input string
hex to decimal
Search WWH ::
Custom Search