Translation from the sixteenth system to the 10th java

I don't understand how this example translates the number. I don't understand the last step... From the line, we take the symbol, then we figure out his index, so we change the letters from the 16system to number, and then... Then what? It's working right, I've been checking it out, but if I'm sitting on the paperwork, and I don't think it's working out for me how the program comes to the right decision... Maybe someone who's a little stiff to untie how it works rightly when the val variable is calculated.
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; }

Number in the sixteenth system, e.g.
A1B
translated into 10th formulaA*16^2 + 1*16 + B
whereA=10
♪B=11
♪ Outcome2587
♪ However, instead of a calculation system16
to a degree at every step, you can use the method, https://ru.wikipedia.org/wiki/%D0%A1%D1%85%D0%B5%D0%BC%D0%B0_%D0%93%D0%BE%D1%80%D0%BD%D0%B5%D1%80%D0%B0 for the calculation of polynomial values at the point. I mean,(A*16 + 1)*16 + B
♪ Thus, the zero irration of the cycle will be computedval=0*16+A=10
Thenval=10*16+1=161
Then161*16+11=2587
♪In fact, on the fingers, the idea is that adding another figure at the end of the line is equivalent to a multiplying of 16 and adding that figure to the sum. Similarly, in the decimal system, the number is 10 and add the number:
123 = 12*10 + 3