To demonstrate String's charAt(int index) and length() methods, I prepared a HexDec hexadecimal-to-decimal conversion application:
Listing 2: HexDec.java
// HexDec.java
// Hexadecimal to Decimal
class HexDec
{
public static void main (String [] args)
{
if (args.length != 1)
{
System.err.println ("usage: java HexDec hex-character-sequence");
return;
}
// Convert argument from hexadecimal to decimal
int dec = 0;
String s = args [0];
for (int i = 0; i < s.length (); i++)
{
char c = s.charAt (i); // Extract character
// If character is an uppercase letter, convert character to
// lowercase
if (Character.isUpperCase (c))
c = Character.toLowerCase (c);
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f'))
{
System.err.println ("invalid character detected");
return;
}
dec <<= 4;
if (c <= '9')
dec += (c - '0');
else
dec += (c - 'a' + 10);
}
System.out.println ("decimal equivalent = " + dec);
}
}
If you want to convert hexadecimal number 7fff to a decimal, use java HexDec 7fff. You then observe the following output:
decimal equivalent = 32767
Caution |
HexDec includes the expression i < s.length () in its for loop header. For long loops, do not call length() in a for loop header because of method call overhead (which can affect performance). Instead, call that method and save its return value before entering the loop, and then use the saved value in the loop header. Example: int len = s.length (); for (int i = 0; i < len; i++). For toy programs, like HexDec, it doesn't matter if I call length() in the for loop header. But for professional programs where performance matters, every time-saving trick helps. (Some Java compilers perform this optimization for you.) |
No comments:
Post a Comment