The code basically summarizes the digits of a number represented as a string. This makes two important assumptions for proper operation:
- The string contains only characters in the range
'0'..'9' - Used character encoding - ASCII
In ASCII, '0' == 48 , '1' == 49 , etc. Thus, '0' - 48 == 0 , '1' - 48 == 1 , etc. That is, subtraction by 48 converts the char values '0'..'9' into int values 0..9 .
Thus, precisely because '0' == 48 , the code will also work with:
sum += s[i] - '0';
In this version, maybe a little more clearly.
You can, of course, do a “reverse” mapping by adding, for example. 5 + '0' == '5' . Similarly, if you have a char containing a letter in the range 'A'..'Z' , you can subtract 'A' from it to get the index of that letter in the range 0..25 .
see also
Related Questions
- How to convert one char to int
- Mapping languages: convert a string of numbers to an array of integers?
- Many examples of converting these numbers using subtraction using
'0' and 48 !
About alternative encodings
As already mentioned, the source code - 48 assumes that the character encoding used is ASCII. - '0' not only improves readability, but also abandons the assumption of ASCII and will work with any encoding, as indicated by the C language, which provides that digital characters must be encoded sequentially in a continuous block.
On the other hand, letters are not being made. Thus, in a rare situation when you use EBCDIC encoding, for example, matching 'A'..'Z' - 0..25 is not as simple as subtracting 'A' , because the letters are NOT encoded sequentially in a continuous block in EBCDIC.
Some programming languages simplify issues by indicating that one particular encoding is used to represent the source code (for example, Java uses Unicode: JLS §3.1 )
see also
Related Questions
- Are the numbers represented in sequence in all text encodings?
polygenelubricants
source share