Sunday, December 4, 2011

Java's character and assorted string classes support text-processing - 4


for (int i = 0; i < 16; i++)
     System.out.println (Character.forDigit (i, 16));

That fragment converts integer numbers 0 through 15 to their character equivalents in the hexadecimal number system and outputs those character equivalents (0 through f).
To complement the forDigit(int digit, int radix) method, Character provides the public static int digit(char c, int radix) method, which converts the c-specified character value in the radix-specified number system, to the value's integer equivalent and returns the result. If c contains a nondigit character for the specified number system or radix is not in the MIN_RADIX/MAX_RADIX range, digit(char c, int radix) returns -1. The following code demonstrates that method:

 char [] digits = { '0', '1', '2', '3', '4', '5', '6', '7',
                   '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'x' };
for (int i = 0; i < digits.length; i++)
     System.out.println (Character.digit (digits [i], 16));

The fragment above converts the digits array's digit characters to their integer equivalents and outputs the results. Apart from the last character, each character represents a hexadecimal digit. (Passing 16 as the radix argument informs digit(char c, int radix) that the number system is hexadecimal.) Because x does not represent a hexadecimal digit, digit(char c, int radix) outputs -1 when it encounters that character.

No comments: