Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c - Why the ASCII value of a digit character is equal to the value plus '0'?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...