Converting from hexadecimal to decimal java
I don't understand how the number is translated in this example. I mean, I don't understand the last step... We take a character from a string, then calculate its index, change the letters from the 16-system to numbers, and then... How then ? Everything works correctly, I checked (compiled), but if I sit on a piece of paper and count, I don't get it at all, how does the program come to the right decision... Can someone slightly step-by-step decompose how the post. string works correctly when calculating val a variable.
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;
}
1 answers
A number in hexadecimal, such as A1B
, is converted to decimal by the formula A*16^2 + 1*16 + B
, where A=10
, and B=11
. Result 2587
. However, instead of raising the base of the number system 16
to a power at each step, you can use a method akin to the Gorner scheme to calculate the values of the polynomials at a point. That is, (A*16 + 1)*16 + B
. Thus, at the zero iteration of the loop, val=0*16+A=10
will be calculated, then val=10*16+1=161
, then 161*16+11=2587
.
Actually, on the fingers of the idea is this: adding the next digit at the end of the line, this is equivalent to multiplying by 16 and adding this digit to the sum. Similarly, in the decimal system, adding a digit means multiplying by 10 and adding a digit: 123 = 12*10 + 3