Home > Backend Development > C++ > 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?

DDD
Release: 2024-12-08 11:40:11
Original
589 people have browsed it

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:

Character ASCII 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.

The above is the detailed content of Why Does Subtracting '0' from a Character Reveal its Numeric Value in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template