C character values arithmetic

2019-07-09 01:57发布

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

4条回答
2楼-- · 2019-07-09 02:25

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 for B (assuming your compiler/platform is using an ASCII-compatible character set).

查看更多
Melony?
3楼-- · 2019-07-09 02:30

The character values of '0' to '9' are guaranteed to be sequential values in all character sets in C.

(C99, 5.1.2p3) "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous."

It means for example that '1' == '0' + 1

查看更多
三岁会撩人
4楼-- · 2019-07-09 02:33

Possible duplicate : See here

Well '0' represent 48 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 you 9.

Note the difference we are sub both chars : '9' - '0', here both are char

查看更多
▲ chillily
5楼-- · 2019-07-09 02:39

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 use 0 as a base value then simple subtraction can convert a 0-9 char into the equivalent int value

查看更多
登录 后发表回答