I do not understand how in this example the number is translated. That is, I do not understand the last step ... From the line we take the character, then we calculate its index, accordingly we 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 I think it doesn’t work out for me at all, as the program comes to the right decision ... Maybe someone will step by step expand as correctly as the last. string when calculating val 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; } 
  • Are you interested in this algorithm in terms of applied knowledge? In Java, there are more humane ways to convert between different number systems. - pavlofff pm

1 answer 1

The number in hexadecimal system, for example, A1B , is converted to decimal by the formula A*16^2 + 1*16 + B , where A=10 and B=11 . The result is 2587 . However, instead of raising the base of the number system 16 at each step, you can use the method, akin to the Horner scheme to calculate the values ​​of 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 the idea is this: adding the next digit to the end of the line, this is equivalent to multiplying by 16 and adding this digit to the sum. Similarly, after all, in the decimal system, the numeration: adding a digit means multiplying by 10 and adding a digit: 123 = 12*10 + 3