如何从一个char把它变成一个int减去字符'0'?

如何从一个char把它变成一个int减去字符'0'?

问题描述:

本方法适用于C,C ++和Java。我想知道它背后的科学。

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

的值字符可以是0-255,其中不同的字符映射到一个这些值。几个数字也被存储起来,以便 0 '9',但他们也通常不存放作为前十个字符值。也就是说,字符 0 没有 0 的ASCII值。的 0 几乎总是 \\ 0 空字符。

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 \0 null character.

不知道什么对ASCII,它是pretty简单的是如何从任何其他数字字符减去 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

所以,同样的,我能做的整数运算与任何字符 numberics ...

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

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

3 5 之间的差额,或 2 0 ASCII表上正好等于面值我们通常认为,当我们看到数字位数。减去字符'0'从,合计在一起,然后加入 0 回末会给我们重新present的字符,这将是这样做简单的数学结果的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.

在code段以上的模拟 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表上:

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