# Thread: hex to dec question

1. ## hex to dec question

Code:
```int htoi(char s[])

{
int i = 0; /* Iterate over s */
int n = 0; /* Built up number */

/* Remove "0x" or "0X" */
if ( s == '0' && s == 'x' || s == 'X' )
i = 2;

while ( s[i] != '\0' )
{
int t;

if ( s[i] >= 'A' && s[i] <= 'F' )

t = s[i] - 'A' + 10;

else if ( s[i] >= 'a' && s[i] <= 'f' )
t = s[i] - 'a' + 10;
else if ( s[i] >= '0' && s[i] <= '9' )
t = s[i] - '0';
else
return n;

n = 16 * n + t;
++i;
}

return n;

}```
Hi, I'm working through the problems in the K&R C book. Anyway I've read around and I can't understand this particular line?

Code:
`t = s[i] - 'A' + 10;`
I don't understand why the 10 is being added. Could anyone please explain? 2. Why is 'A' is subtracted from s[i]? Could you please explain? 3. EDIT: Ok so I think I understand it. A = 10 in hex, B = 11 ...F = 16. The reason the numeric value of A is being substracted and then 10 added to it is so that the number can be repesented by it's hex value. For example:

If s[i] = 'B' which has a deciman value of 66. Then

t = s[i] - 'A' + 10;

will equal to t = 66 - 65 + 10 which is 11.
11 is the hex value of B. 4. Originally Posted by rbz EDIT: Ok so I think I understand it.
That's exactly it. As you can see it's only done if s[i] is between 'A' and 'F' or 'a' and 'f'. For all other cases '0' is subtracted since 0-9 is covered in the decimal set. 5. I know this is not very common, but I always write it like this:
Code:
`BinVal = AsciiVal - 'A' + 0xA;`
This to me makes it clear that you're moving a value from being based at 'A' to being based at 0xA, and feels somewhat like you're removing a magic number too. Popular pages Recent additions 