C - 将 char 转换为 int [英] C - Convert char to int
问题描述
我知道要将任何给定的 char 转换为 int,此代码是可能的[除了 atoi()]:
I know that to convert any given char to int, this code is possible [apart from atoi()]:
int i = '2' - '0';
但我从来不明白它是如何工作的,'0' 的意义是什么,我似乎没有在网上找到任何关于它的解释.
but I never understood how it worked, what is significance of '0' and I don't seem to find any explanation on the net about that.
提前致谢!!
推荐答案
在 C 中,字符文字的类型为 int
.[字符文字/IBM]
In C, a character literal has type int
. [Character Literals/IBM]
在您的示例中,'0'
的数值为 48,'2'
的数值为 50.当您执行 '2'- '0'
你得到 50 - 48 = 2
.这适用于从 0 到 9 的 ASCII 数字.
In your example, the numeric value of '0'
is 48, the numeric value of '2'
is 50. When you do '2' - '0'
you get 50 - 48 = 2
. This works for ASCII numbers from 0 to 9.
请参阅 ASCII 表以获得更好的图片.
See ASCII table to get a better picture.
感谢@ouah 的更正.
Thanks to @ouah for correction.
这篇关于C - 将 char 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!