Java Reference
In-Depth Information
5.8.3 Case Study: Converting Decimals to Hexadecimals
Hexadecimals are often used in computer systems programming (see Appendix F for an
introduction to number systems). How do you convert a decimal number to a hexadecimal
number? To convert a decimal number
d
to a hexadecimal number is to find the hexadecimal
digits
h
n
,
h
n
-
1
,
h
n
-
2
,
c
,
h
2
,
h
1
, and
h
0
such that
16
n
16
n
-
1
16
n
-
2
d
=
h
n
*
+
h
n
-
1
*
+
h
n
-
2
*
+
g
16
2
16
1
16
0
+
h
2
*
+
h
1
*
+
h
0
*
These hexadecimal digits can be found by successively dividing
d
by 16 until the quotient is
0. The remainders are
h
0
,
h
1
,
h
2
,
c
,
h
n
-
2
,
h
n
-
1
, and
h
n
. The hexadecimal digits include the
decimal digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, plus A, which is the decimal value 10; B, which
is the decimal value 11; C, which is 12; D, which is 13; E, which is 14; and F, which is 15.
For example, the decimal number
123
is
7B
in hexadecimal. The conversion is done as
follows. Divide
123
by
16
. The remainder is
11
(
B
in hexadecimal) and the quotient is
7
.
Continue divide
7
by
16
. The remainder is
7
and the quotient is
0
. Therefore
7B
is the
hexadecimal number for
123
.
0
7
Quotient
16
7
0
7
16
123
112
11
Remainder
h
1
h
0
Listing 5.11 gives a program that prompts the user to enter a decimal number and converts
it into a hex number as a string.
L
ISTING
5.11
Dec2Hex.java
1
import
java.util.Scanner;
2
3
public class
Dec2Hex {
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 decimal integer
10 System.out.print(
"Enter a decimal number: "
);
11
int
decimal = input.nextInt();
input decimal
12
13
// Convert decimal to hex
14 String hex =
""
;
15
16
decimal to hex
while
(decimal !=
0
) {
17
int
hexValue = decimal %
16
;
18
19
// Convert a decimal value to a hex digit
20
char
hexDigit = (hexValue <=
9
&& hexValue >=
0
) ?
21 (
char
)(hexValue +
'0'
) : (
char
)(hexValue -
10
+
'A'
);
22
23
hex = hexDigit + hex;
Search WWH ::
Custom Search