Reputation: 9456
The algorithm below converts hex to decimal, but I've confused, how this solution works?
public static int hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
I had known only one approach to do that before I found out this one.
I mean, everyone knows:
X*16^Y
where X
is the number you want to convert and Y
is the position for the number (begging from the end to the start).
So, if you want to convert DA145
to decimal would be...
*(5 * 16^0) + (4 * 16^1) + (1 * 16^2) + (10 * 16^3) + (13 * 16^4)*
Upvotes: 0
Views: 96
Reputation: 14360
This algorithm uses the fact that we can calculate 16^Y by repeatedly multiply together 16's and also that we can factor out common multiplications by 16. From your example you would instead end at:
13*16 + 10)*16 + 1)*16 + 4)*16 + 5
I've omitted the leading parentheses, as you see it happens to be that 13 is in effect multiplied with 16 four times.
Upvotes: 5
Reputation: 1680
The algorithm does pretty much the same as you would do it. It takes a String and compares every single char with the given value. This value is evaluated by digits, at which position it stands (e.g. A is in the 10th position, since we start counting with 0). This allows to easily change it e.g. to a 17 digit system instead of hexadezimal.
Edit: About the powers of 16, look at @skykings answer.
Upvotes: 1