patternjavaModerate
Hex to Decimal converter
Viewed 0 times
hexdecimalconverter
Problem
Any feedback is welcome:
public class HexToDecimal {
static String hexRep = "0123456789ABCDEF";
public static void main(String[] args) {
System.out.println(HexToDecimal.hexToDecimal("AB"));
}
public static int hexToDecimal(String hex) {
int counter = hex.length()-1;
int sum = 0;
for (char c:hex.toCharArray()) {
int i = hexRep.indexOf(c);
sum = (int) (sum + (Math.pow(16,counter))*i);
counter--;
}
return sum;
}
}Solution
Java's
W.R.T. your code, here are some observations:
Integer class has a built-in method to parse a hex number (string) into an int:Integer.valueOf("AB", 16)W.R.T. your code, here are some observations:
hexRepshould befinal
- Ideally your method should also accept lower-case text (just call
toUpperCase()on the string)
- Include some unit tests perhaps?
- I wouldn't put that single method in a class of its own. More appropriate would be to put it in a more general utility class
Code Snippets
Integer.valueOf("AB", 16)Context
StackExchange Code Review Q#79072, answer score: 15
Revisions (0)
No revisions yet.