从 char 中减去字符“0"如何将其更改为 int?

2022-01-12 00:00:00 c char int c++ java

此方法适用于 C、C++ 和 Java.我想知道它背后的科学原理.

This method works in C, C++ and Java. I would like to know the science behind it.

推荐答案

char 的值可以是 0-255,其中不同的字符映射到这些值之一.数字也按 '0''9' 的顺序存储,但它们通常也不作为前十个 char 存储价值观.也就是说,字符 '0' 没有 0 的 ASCII 值.0 的 char 值几乎总是 空字符.

The value of a char can be 0-255, where the different characters are mapped to one of these values. The numeric digits are also stored in order '0' through '9', but they're also not typically stored as the first ten char values. That is, the character '0' doesn't have an ASCII value of 0. The char value of 0 is almost always the null character.

在不了解 ASCII 的情况下,从任何其他数字字符中减去 '0' 字符将导致原始字符的 char 值非常简单.

Without knowing anything else about ASCII, it's pretty straightforward how subtracting a '0' character from any other numeric character will result in the char value of the original character.

所以,这是简单的数学:

So, it's simple math:

'0' - '0' = 0  // Char value of character 0 minus char value of character 0
// In ASCII, that is equivalent to this:
48  -  48 = 0 // '0' has a value of 48 on ASCII chart

因此,同样,我可以使用任何 char 数字进行整数数学...

So, similarly, I can do integer math with any of the char numberics...

(('3' - '0') + ('5' - '0') - ('2' - '0')) + '0') = '6'

3520在ASCII图表上的区别正好等于当我们看到那个数字时,我们通常会想到的面值.从每个中减去 char '0',将它们加在一起,然后在末尾添加一个 '0' 将为我们提供代表字符的 char 值做那个简单的数学运算的结果.

The difference between 3, 5, or 2 and 0 on the ASCII chart is exactly equal to the face value we typically think of when we see that numeric digit. Subtracting the char '0' from each, adding them together, and then adding a '0' back at the end will give us the char value that represent the char that would be the result of doing that simple math.

上面的代码片段模拟了 3 + 5 - 2,但在 ASCII 中,它实际上是这样做的:

The code snippet above emulates 3 + 5 - 2, but in ASCII, it's actually doing this:

((51 - 48) + (53 - 48) - (50 - 48)) + 48) = 54

因为在 ASCII 图表上:

Because on the ASCII chart:

0 = 48
2 = 50
3 = 51
5 = 53
6 = 54

相关文章