19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

192 Chapter 5 Methods<br />

For example, the decimal number 123 is 7B in hexadecimal. The conversion is done as<br />

follows. Divide 123 by 16. The remainder is 11 (B in hexadecimal) and the quotient is 7.<br />

Continue <strong>to</strong> divide 7 by 16. The remainder is 7 and the quotient is 0. Therefore 7B is the hexadecimal<br />

number for 123.<br />

0<br />

16 7<br />

0<br />

7<br />

7<br />

16 123<br />

112<br />

11<br />

Quotient<br />

Remainder<br />

h 1<br />

h 0<br />

Listing 5.8 gives a program that prompts the user <strong>to</strong> enter a decimal number and converts<br />

it in<strong>to</strong> a hex number as a string.<br />

input decimal<br />

decimal <strong>to</strong> hex<br />

get a hex char<br />

get a letter<br />

LISTING 5.8<br />

Decimal2HexConversion.java<br />

1 import java.util.Scanner;<br />

2<br />

3 public class Decimal2HexConversion {<br />

4 /** Main method */<br />

5 public static void main(String[] args) {<br />

6 // Create a Scanner<br />

7 Scanner input = new Scanner(System.in);<br />

8<br />

9 // Prompt the user <strong>to</strong> enter a decimal integer<br />

10 System.out.print("Enter a decimal number: ");<br />

11 int decimal = input.nextInt();<br />

12<br />

13 System.out.println("The hex number for decimal " +<br />

14 decimal + " is " + decimalToHex(decimal));<br />

15 }<br />

16<br />

17 /** Convert a decimal <strong>to</strong> a hex as a string */<br />

18<br />

19<br />

public static String decimalToHex(int decimal) {<br />

String hex = "";<br />

20<br />

21 while (decimal != 0) {<br />

22 int hexValue = decimal % 16;<br />

23 hex = <strong>to</strong>HexChar(hexValue) + hex;<br />

24 decimal = decimal / 16;<br />

25 }<br />

26<br />

27 return hex;<br />

28 }<br />

29<br />

30 /** Convert an integer <strong>to</strong> a single hex digit in a character */<br />

31<br />

32<br />

public static char <strong>to</strong>HexChar(int hexValue) {<br />

if (hexValue = 0)<br />

33 return (char)(hexValue + '0');<br />

34 else // hexValue = 10<br />

35 return (char)(hexValue - 10 + 'A');<br />

36 }<br />

37 }

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!