"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Subtracting '0' from a Character Reveal its Numeric Value in C?

Why Does Subtracting '0' from a Character Reveal its Numeric Value in C?

Published on 2024-12-21
Browse:384

Why Does Subtracting '0' from a Character Reveal its Numeric Value in C?

Decoding Char Values: Why Subtracting '0' Divulges the Numeric Representation

A puzzling question arises: why does subtracting '0' from a character in C reveal the numeric value it represents?

To unravel this enigma, let's delve into the realm of ASCII (American Standard Code for Information Interchange), which assigns numerical codes to each character. '0' holds the first position in this numeric sequence, with subsequent characters incrementally assigned higher values.

For instance, '9' represents the numeric value 57, while '0' corresponds to 48. By subtracting '0' from a character, we essentially calculate the difference between its ASCII code and the ASCII code of '0'.

Consider the example: char c = '9'; int x = (int)(c - '0');
Here, '9' has an ASCII code of 57. Subtracting '0' (which has an ASCII code of 48) yields 57 - 48 = 9, which is precisely the numeric value represented by '9'.

The following ASCII table further illustrates this concept:

CharacterASCII Code
'0'48
'1'49
'9'57

By subtracting '0' from any char, we can effectively decode the numerical value it represents, a technique commonly employed in various programming applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3