Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

ascii

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?

like image 712
Hommer Smith Avatar asked Feb 12 '13 11:02

Hommer Smith


People also ask

What is the relationship between the ASCII value of a digit and the actual value it represents?

Character form of a decimal digit In ASCII, the number character is not the same as the actual number value. For example, the ASCII value 011 0100 will print the character '4', the binary value is actually equal to the decimal number 52. Therefore ASCII cannot be used for arithmetic.

What is the purpose of the ASCII character set?

ASCII (American Standard Code for Information Interchange) is the most common character encoding format for text data in computers and on the internet. In standard ASCII-encoded data, there are unique values for 128 alphabetic, numeric or special additional characters and control codes.


1 Answers

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.
like image 161
Jon Avatar answered Sep 28 '22 20:09

Jon