A
A
AlexMark2016-07-09 16:06:36
Java
AlexMark, 2016-07-09 16:06:36

How is hexadecimal converted to decimal in this example?

public class Hex2Decimal {

    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 don't understand how the number is translated in this example.
That is, I don't understand the last step... We take a character from the string, then calculate its index, change the letters from the 16-system to numbers accordingly, and then... How then? Everything works correctly, I checked (compiled), but if I sit on a piece of paper and think, it doesn’t work for me at all, how the program comes to the right decision ... Maybe someone can decompose a little step by step how the last works correctly. string when evaluating the val variable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Leonid, 2016-07-09
@AlexMark

Maybe it will be clearer this way:
FE=(16*0+15)*16+14=254
123=((16*0+1)*16+2)*16+3=291

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question