I have been reading from the book "The C Programming Language" learning C, and I stumbled upon the arithmetic s[i] - '0'
which they said that it gives the numeric value of the character stored in s[i]. I didn't quite understand it, how could it give the value by subtraction?
Note This is used in the atoi function, which converts a string of digits into its numeric equivalent.
Thanks
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Basically, what you need to understand is that on a modern computer, all information is stored digitally as a sequence of bytes. It's up to each program to decide how to interpret each byte. So a character is nothing but one or more bytes - a numerical value which usually represents a human-readable letter or symbol. For example, in ASCII, the letter 'A' is represented by the numerical value 65.
What this means is that in certain programming languages, such as C, you can treat characters as numerical values. For example, in C the expression
'A' + 1
would give you 66, which happens to be the ASCII value forB
(assuming your compiler/platform is using an ASCII-compatible character set).The character values of
'0'
to'9'
are guaranteed to be sequential values in all character sets in C.It means for example that
'1' == '0' + 1
Possible duplicate : See here
Well
'0'
represent48
in character set. So subtracting it('0'
) with any other character value like this'1'
,'2'
will give respective number, so'9'
-'0'
will give you9
.Note the difference we are sub both chars :
'9'
-'0'
, here both arechar
Under the hood a
char
is represented by a numeric value. The characters for the numbers 0-9 are stored in ascending numeric values. If we use0
as a base value then simple subtraction can convert a 0-9 char into the equivalent int value