从 char 中减去字符“0"如何将其更改为 int? [英] How does subtracting the character '0' from a char change it into an int?

查看:17
本文介绍了从 char 中减去字符“0"如何将其更改为 int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此方法适用于 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

这篇关于从 char 中减去字符“0"如何将其更改为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆