Search code examples
ccharasciiexpressionatoi

C character values arithmetic


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


Solution

  • 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).