c - Why does this code work to convert hexadecimal to decimal -


this code convert 1 hexadecimal digit decimal value.

int value; // ch char variable holding hexadecimal digit if (isxdigit(ch))     if (isdigit(ch))         value = ch - '0';     else         value = tolower(ch) - 'a' + 10; else     fprintf(stderr, "%c not valid hex digit", ch); 

i don't understand how works though. can see different things subtracted char variable depending on whether number or letter. can understand part number gets converted, don't understand why 10 has added value when character letter.

the subtraction of tolower(ch) - 'a' map character number in range 0..5 letters a..f. however, (decimal) value of hexadecimal digit a16 1010, move range 10..15 needs be, 10 added.

perhaps helps:

+---------+------------+-----------------+-------------+ character | subtracted | resulting value | digit value | +---------+------------+-----------------+-------------+ |   '0'   |     '0'    |       0         |       0     | |   '1'   |     '0'    |       1         |       1     | |   '2'   |     '0'    |       2         |       2     | |   '3'   |     '0'    |       3         |       3     | |   '4'   |     '0'    |       4         |       4     | |   '5'   |     '0'    |       5         |       5     | |   '6'   |     '0'    |       6         |       6     | |   '7'   |     '0'    |       7         |       7     | |   '8'   |     '0'    |       8         |       8     | |   '9'   |     '0'    |       9         |       9     | |   'a'   |     'a'    |       0         |      10     | |   'b'   |     'a'    |       1         |      11     | |   'c'   |     'a'    |       2         |      12     | |   'd'   |     'a'    |       3         |      13     | |   'e'   |     'a'    |       4         |      14     | |   'f'   |     'a'    |       5         |      15     | +---------+------------+-----------------+-------------+ 

notice how "resulting value" column resets 0 @ 'a', not needs according final "digit value" column, shows each hexadecimal digit's value in decimal.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -