Understanding the Char-to-int Conversion in C: Why Subtracting '0' Yields the Numeric Value
In C programming, a peculiar operation involving characters and integers can evoke curiosity: subtracting '0' from an ASCII code of a char produces the number represented by that char. This perplexing behavior warrants an exploration to grasp its underlying logic.
The key lies in the representation of characters in computers. Each character is assigned a numerical value, known as its ASCII code, which determines its position in the ASCII character set. For instance, the character '0' corresponds to the ASCII code 48, while '9' corresponds to code 57.
The operation of subtracting '0' from the ASCII code effectively removes the numeric value associated with the '0' character. This is because '0' is the first character in the ASCII set, with a code of 48. As a result, subtracting 48 from any other ASCII code effectively shifts down the numerical values by 48, revealing the original number represented by that char.
For example, when we subtract '0' from the ASCII code of '9' (57), we get 57 - 48 = 9, which corresponds to the number represented by the character '9'.
This mechanism provides a convenient way to convert character representations of numbers into their numeric counterparts, facilitating various programming operations where numerical handling is required.
The above is the detailed content of Why Does Subtracting '0' from a Character's ASCII Value in C Give Its Numeric Equivalent?. For more information, please follow other related articles on the PHP Chinese website!