The Best Source For HiTech
Hello, I'm currently working on a java program wherein the user will input their chosen number, its current base, and the desired base output then program will of course convert it to that and output the number in its new base. I have it figured out for the most part but I was wondering if anyone could give me some tips or show me how to use base 16 since it involves letters. i was thinking about using string tokenizer to go through the string and replace all the letters with their numerical value then proceed to the conversion as normal but that seems impractical with double digit numbers. Also it currently only accepts numbers in the base 10 format, how would you recommend that i go about implementing the other bases as a choice for format. My current idea for this is have them input the number and its current base, convert that to base 10, then run it through the program properly, but again this seems very impractical and difficult to do. If anyone could show me an example program that does this or just give me some pointers I'd really appreciate it.
We're the best source for HiTech information
Silent
February 8th, 2010 at 6:45 am
Forget StringTokenizer. It’s somewhat obsolete these days.
Instead, use the two-argument parseInt method on the Integer class. The first argument is a String, the second an int. This method parses the given String into an int, using the second argument as a base. Unless you’re using some non-standard implementation of the JDK, this base must be greater than 1 and no more than 36. So, for example,
int num = Integer.parseInt(“123ABC”, 16);
will convert “123ABC” into an integer, treating it as a base-16 number.
The Integer class also has a static toString() method with two arguments that works much the same way. For example:
String hex = Integer.toString(4656, 16);
will print out the hexadecimal representation of 4656.