Well, ok, short explanation. A hexadecimal number is basically a base 16 number, meaning it has digits going from 0-15 (10-15 are represented by the letters a-f). A hex number consists of hex digits, which represent a power of 16 (starting at 16 power 0, usually ascending from right to left).
This means that 1AF in hexadecimal stands for 1*16^2(1*256) + 10*16^1(10*16) + 15*16^0(15*1). To convert a hex string to a deximal integer, we first check each character (at this point, you should automatically think "loop") for whether it is a legal character or not (which means, it may be either a digit from 0-9, a letter from a-f or a letter from A-F). Assuming that the string is encoded in ASCII, this means that a letter must either be in the range of 48-58 (digits 0-9), or in the range of 65-70 (letters A-F) or in the range 97-102 (letters a-f).
While we are at that, we can also start adding up the digits. Since a string is read from left to right, the first digit we encounter will be the highest power of 16, the last digit will be the 0th power of 16. Since we already know the size (length) of the string, we know that the first digit will be the (stringlength-1)th power of 16 (since the last digit is the 0th). Now, depending on whether it is a digit, an upper case letter or a lower case letter, we add (charactervalue-48) or (charactervalue-55) or (charactervalue-87) times the power of 16 to the sum.
At the end, we just return the sum. Try reading this carefully, if you get confused by anything, try drawing every single step on a sheet of paper before asking for help.
EDIT:
Um... no... Please burn that book, and also post the title of it so that we may black list it. |
So, uh,
exercises - this is obviously one- are a bad thing in a teaching book? What the heck?