Why the ASCII value of a digit character is equal

2020-04-08 07:07发布

问题:

Why when we want to convert an ASCII value of a digit into an integer, we need to do:

value - '0' ?

And the other way around, to convert Integer to ASCII, we need to do:

value + '0'

Why is that?

回答1:

Because the integral values of the digit characters are guaranteed by the C standard to be consecutive.

Therefore '1' - '0' == 1, '2' - '0' == 2, etc. from which you can infer that your formulas really do work.

Sidenotes:

  1. Since this is guaranteed by the standard, it works even if the target platform does not use ASCII.
  2. Conversely, if the standard did not mandate this (it does not do so with the values of the letters) then this technique would not be portable; it would be dependent on the target system using ASCII.


回答2:

Because ASCII digits are encoded consequently one after another.

Say '0' == 48. Then '1' == 49, '2' == 50 and so on.

If you think about it, '2' - '0' == 50 - 48 == 2. Similarly, 2 + '0' == 2 + 48 == 50 == '2'.



回答3:

The ASCII values of the digits are all in sequence. So 0 simply marks the start of the sequence at ASCII codepoint 48, continuing up to 9 at position 57.



回答4:

Just because codes of digits are in sequence (48 .. 57) as defined by ASCII standard.



回答5:

ASCII value is a position number of a symbol in the table. So you use '0' symbol position number as an offset of the digit symbols, adding an integer digit value to it you can calculate its position number.



标签: c ascii